import { and, asc, eq, lt } from 'drizzle-orm'
import { getOrderById, order, type Order, type OrdersSchema } from '@platform-modules/commerce-orders'
import type { Querier } from '@platform-modules/db'
import type { CheckoutDeps } from '../types.js'

const DEFAULT_OLDER_THAN_MS = 15 * 60 * 1000
const DEFAULT_LIMIT = 100

export async function reconcileStuckCharges<S extends OrdersSchema>(
  deps: CheckoutDeps<S>,
  opts?: { olderThanMs?: number; limit?: number },
): Promise<{ stuck: Order[] }> {
  const olderThanMs = opts?.olderThanMs ?? DEFAULT_OLDER_THAN_MS
  const cutoff = new Date(Date.now() - olderThanMs)

  const rows = await deps.db
    .select({ id: order.id })
    .from(order)
    .where(and(eq(order.status, 'charging'), lt(order.updatedAt, cutoff)))
    .orderBy(asc(order.updatedAt))
    .limit(opts?.limit ?? DEFAULT_LIMIT)

  const stuck: Order[] = []
  for (const row of rows) {
    const loaded = await getOrderById(deps.db as unknown as Querier<OrdersSchema>, row.id, {
      isAdmin: true,
    })
    if (loaded) {
      stuck.push(loaded)
    }
  }

  return { stuck }
}
