import { eq } from 'drizzle-orm'
import type { Querier } from '@platform-modules/db'
import {
  assembleOrder,
  loadOrderChildren,
  rowToBuyerRef,
} from './order-assembly.js'
import { order, type OrdersSchema } from './schema.js'
import { assertUuid, type Actor, type Order } from './types.js'

export async function getOrderById(
  q: Querier<OrdersSchema>,
  id: string,
  actor: Actor,
): Promise<Order | null> {
  assertUuid(id, 'orderId')

  const [row] = await q.select().from(order).where(eq(order.id, id))
  if (!row) {
    return null
  }

  const buyerRef = rowToBuyerRef(row)

  // Fast-path entitlement checks that need no child rows — eliminates timing oracle for
  // non-entitled requests (a non-owner UUID probe incurs only one query, not four).
  if (actor.isAdmin === true) {
    const { lines, splits, steps } = await loadOrderChildren(q, id)
    return assembleOrder(row, lines, splits, steps)
  }
  if (actor.userId !== undefined && 'userId' in buyerRef && buyerRef.userId === actor.userId) {
    const { lines, splits, steps } = await loadOrderChildren(q, id)
    return assembleOrder(row, lines, splits, steps)
  }

  // Vendor entitlement requires line data; load children only now.
  if (actor.vendorId !== undefined) {
    const { lines, splits, steps } = await loadOrderChildren(q, id)
    if (lines.some((line) => line.vendorId === actor.vendorId)) {
      return assembleOrder(row, lines, splits, steps)
    }
  }

  return null
}
