import { and, eq } from 'drizzle-orm'
import type { Transaction } from '@platform-modules/db'
import { OrderNotChargeableError } from './errors.js'
import { order, type OrdersSchema } from './schema.js'
import { assertUuid } from './types.js'

export async function failOrder(
  tx: Transaction<OrdersSchema>,
  orderId: string,
  reason: string,
): Promise<void> {
  assertUuid(orderId, 'orderId')

  const now = new Date()
  const [updated] = await tx
    .update(order)
    .set({ status: 'failed', failureReason: reason, updatedAt: now })
    .where(and(eq(order.id, orderId), eq(order.status, 'charging')))
    .returning({ id: order.id })

  if (updated) {
    return
  }

  const [existing] = await tx.select().from(order).where(eq(order.id, orderId))

  if (!existing) {
    throw new OrderNotChargeableError(orderId)
  }

  if (existing.status === 'failed') {
    return
  }

  throw new OrderNotChargeableError(orderId)
}
