import { eq } from 'drizzle-orm'
import { describe, expect, it } from 'vitest'
import { createPgliteClient } from '@platform-modules/db/pglite'
import { claimForCharge } from './claim-for-charge.js'
import { createOrder } from './create-order.js'
import { isOrderNotChargeableError } from './errors.js'
import { pushSchema } from './migrate.js'
import { order, 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'

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('claimForCharge', () => {
  it('transitions pending to charging and returns the full order', async () => {
    const db = await freshDb()
    const created = await db.transaction((tx) => createOrder(tx, baseOrder()))

    const claimed = await db.transaction((tx) => claimForCharge(tx, created.id))

    expect(claimed.status).toBe('charging')
    expect(claimed.id).toBe(created.id)
    expect(claimed.lines).toHaveLength(1)
    expect(claimed.splits).toHaveLength(1)

    const [row] = await db.select().from(order).where(eq(order.id, created.id))
    expect(row?.status).toBe('charging')
  })

  it('rejects a second claim with OrderNotChargeableError', async () => {
    const db = await freshDb()
    const created = await db.transaction((tx) => createOrder(tx, baseOrder()))

    await db.transaction((tx) => claimForCharge(tx, created.id))

    await expect(db.transaction((tx) => claimForCharge(tx, created.id))).rejects.toSatisfy(
      (e) => isOrderNotChargeableError(e),
    )
  })
})
