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

type SqlRow = Record<string, unknown>

function rows(res: unknown): SqlRow[] {
  return (Array.isArray(res) ? res : (res as { rows?: SqlRow[] }).rows) ?? []
}

export async function sweepStaleReservations(
  q: Querier<InventorySchema>,
  now: Date,
): Promise<{ released: number }> {
  const nowIso = now.toISOString()

  const res = await q.execute(sql`
    UPDATE stock_reservation
    SET released_at = ${nowIso}::timestamptz
    WHERE expires_at < ${nowIso}::timestamptz
      AND consumed_at IS NULL
      AND released_at IS NULL
    RETURNING id
  `)

  return { released: rows(res).length }
}
