import { eq } from 'drizzle-orm'
import { describe, expect, it } from 'vitest'
import { createPgliteClient } from '@platform-modules/db/pglite'
import { createOrder } from './create-order.js'
import { isOrderValidationError } from './errors.js'
import { pushSchema } from './migrate.js'
import { orderStep, ordersSchema } from './schema.js'
import { recordStep } from './record-step.js'
import type { NewOrder } from './types.js'

const VARIANT_A = '11111111-1111-4111-8111-111111111111'
const BUYER_ID = '33333333-3333-4333-8333-333333333333'

async function freshDb() {
  const db = createPgliteClient({ schema: ordersSchema })
  await pushSchema(db)
  return db
}

function baseOrder(): NewOrder {
  return {
    idempotencyKey: crypto.randomUUID(),
    buyerRef: { userId: BUYER_ID },
    currency: 'USD',
    priceMode: 'exclusive',
    subtotal: 1000n,
    tax: 100n,
    discount: 0n,
    total: 1100n,
    lines: [
      {
        variantId: VARIANT_A,
        kind: 'physical',
        qty: 2,
        unitPrice: 500n,
        lineTotal: 1000n,
        currency: 'USD',
        vendorId: null,
      },
    ],
    splits: [{ vendorId: null, amount: 1100n, funder: 'platform' }],
  }
}

describe('recordStep', () => {
  it('returns true on first insert and false on replay with one row', async () => {
    const db = await freshDb()
    const created = await db.transaction((tx) => createOrder(tx, baseOrder()))
    const stepResult = { granted: true, licenseId: 'lic_123' }

    const first = await db.transaction((tx) =>
      recordStep(tx, created.id, 'grant-license', stepResult),
    )
    const second = await db.transaction((tx) =>
      recordStep(tx, created.id, 'grant-license', stepResult),
    )

    expect(first).toBe(true)
    expect(second).toBe(false)

    const rows = await db.select().from(orderStep).where(eq(orderStep.orderId, created.id))
    expect(rows).toHaveLength(1)
    expect(rows[0]?.stepId).toBe('grant-license')
  })

  it('returns true for a distinct stepId', async () => {
    const db = await freshDb()
    const created = await db.transaction((tx) => createOrder(tx, baseOrder()))

    const first = await db.transaction((tx) =>
      recordStep(tx, created.id, 'grant-license', { ok: true }),
    )
    const second = await db.transaction((tx) =>
      recordStep(tx, created.id, 'send-receipt', { sent: true }),
    )

    expect(first).toBe(true)
    expect(second).toBe(true)

    const rows = await db.select().from(orderStep).where(eq(orderStep.orderId, created.id))
    expect(rows).toHaveLength(2)
  })

  it('rejects empty stepId with OrderValidationError', async () => {
    const db = await freshDb()
    const created = await db.transaction((tx) => createOrder(tx, baseOrder()))

    await expect(
      db.transaction((tx) => recordStep(tx, created.id, '', { ok: true })),
    ).rejects.toSatisfy((e) => isOrderValidationError(e))
  })
})
