import { describe, expect, it } from 'vitest'
import { createPgliteClient } from '@platform-modules/db/pglite'
import { isInventoryValidationError } from './errors.js'
import { getAvailability } from './get-availability.js'
import { pushSchema } from './migrate.js'
import { release } from './release.js'
import { reserve } from './reserve.js'
import { inventorySchema } from './schema.js'
import { setInventory } from './set-inventory.js'

const SKU_ID = '44444444-4444-4444-8444-444444444444'
const NOW = new Date('2026-06-19T12:00:00.000Z')

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

describe('release', () => {
  it('frees a hold so getAvailability rises and is idempotent on retry', async () => {
    const db = await freshDb()
    await db.transaction((tx) => setInventory(tx, { skuId: SKU_ID, quantityTotal: 10 }))

    const { reservationId } = await db.transaction((tx) =>
      reserve(tx, { skuId: SKU_ID, qty: 4, holderRef: 'h1', now: NOW }),
    )

    expect(await getAvailability(db, SKU_ID)).toBe(6)

    await db.transaction((tx) => release(tx, reservationId))
    expect(await getAvailability(db, SKU_ID)).toBe(10)

    await db.transaction((tx) => release(tx, reservationId))
    expect(await getAvailability(db, SKU_ID)).toBe(10)
  })

  it('rejects a malformed reservationId with InventoryValidationError', async () => {
    const db = await freshDb()
    await expect(
      db.transaction((tx) => release(tx, 'bad-id')),
    ).rejects.toSatisfy((e) => isInventoryValidationError(e))
  })
})
