import type { Transaction } from '@platform-modules/db'
import { OrderValidationError } from './errors.js'
import { orderStep, type OrdersSchema } from './schema.js'
import { assertUuid, type StepRecord } from './types.js'

export async function recordStep(
  tx: Transaction<OrdersSchema>,
  orderId: string,
  stepId: string,
  result: StepRecord,
): Promise<boolean> {
  assertUuid(orderId, 'orderId')

  if (stepId.length === 0) {
    throw new OrderValidationError('stepId')
  }

  const inserted = await tx
    .insert(orderStep)
    .values({ orderId, stepId, result })
    .onConflictDoNothing({ target: [orderStep.orderId, orderStep.stepId] })
    .returning({ id: orderStep.id })

  return inserted.length > 0
}
