import { eq, sql } from 'drizzle-orm'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { createOrder } from './create-order.js'
import { startPg } from './pg-harness.js'
import { orderStep } from './schema.js'
import { recordStep } from './record-step.js'
import type { TransactionalDatabase } from '@platform-modules/db'
import type { OrdersSchema } from './schema.js'
import type { NewOrder } from './types.js'

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

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 concurrency (real Postgres)', () => {
  let db: TransactionalDatabase<OrdersSchema>
  let stop: (() => Promise<void>) | undefined

  beforeAll(async () => {
    const pg = await startPg()
    db = pg.db
    stop = pg.stop
  }, 120_000)

  afterAll(async () => {
    await stop?.()
  }, 30_000)

  it('concurrent duplicate step: one true, one false, exactly one row', async () => {
    const created = await db.transaction((tx) => createOrder(tx, baseOrder()))
    const stepResult = { granted: true, licenseId: 'lic_concurrent' }

    const results = await Promise.all([
      db.transaction((tx) => recordStep(tx, created.id, 'grant-license', stepResult)),
      db.transaction((tx) => recordStep(tx, created.id, 'grant-license', stepResult)),
    ])

    const trueCount = results.filter((r) => r === true).length
    const falseCount = results.filter((r) => r === false).length

    expect(trueCount).toBe(1)
    expect(falseCount).toBe(1)

    const countRes = (await db.execute(sql`
      SELECT COUNT(*)::int AS count FROM order_step WHERE order_id = ${created.id}::uuid
    `)) as unknown as { rows?: Array<{ count: number }> } | Array<{ count: number }>
    const rows = (Array.isArray(countRes) ? countRes : countRes.rows) ?? []
    expect(Number(rows[0]?.count)).toBe(1)

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