import { sql } from 'drizzle-orm'
import type { Transaction } from '@platform-modules/db'
import type { InventorySchema } from './schema.js'
import { assertUuid } from './types.js'

type SqlRow = Record<string, unknown>

function firstRow(res: unknown): SqlRow | undefined {
  const rows = (Array.isArray(res) ? res : (res as { rows?: SqlRow[] }).rows) ?? []
  return rows[0]
}

export async function consume(
  tx: Transaction<InventorySchema>,
  reservationId: string,
): Promise<boolean> {
  assertUuid(reservationId, 'reservationId')

  const res = await tx.execute(sql`
    WITH mark AS (
      UPDATE stock_reservation
      SET consumed_at = now()
      WHERE id = ${reservationId}::uuid
        AND consumed_at IS NULL
        AND released_at IS NULL
      RETURNING sku_id, qty, id
    ),
    sold AS (
      UPDATE inventory_item ii
      SET quantity_sold = ii.quantity_sold + mark.qty, updated_at = now()
      FROM mark
      WHERE ii.sku_id = mark.sku_id
    )
    SELECT id FROM mark
  `)

  return firstRow(res)?.id !== undefined
}
