import { NextResponse } from 'next/server'
import { resolveBillingContext } from '@/lib/data/billing-context'
import { createPurchaseFromCart, listTripPurchases } from '@/lib/data/purchases'
import { requireCartAccess } from '@/lib/purchase-api'

/**
 * Turn the open cart into a purchase (task §5.2, §16). Idempotent on the
 * cart: a retry returns the same purchase with `reused: true`. The body is
 * ignored — the server re-quotes from the cart and the catalog.
 */
export async function POST(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  const guard = await requireCartAccess(id)
  if (!guard.ok) return guard.response
  const billing = await resolveBillingContext(guard.user, guard.trip)
  if (!billing.ok) return NextResponse.json({ error: 'Your active company cannot bill for this trip.' }, { status: 403 })
  const result = await createPurchaseFromCart({
    trip: guard.trip,
    userId: guard.user.id,
    actorLabel: guard.actorLabel,
    billing: billing.billing,
    companyId: billing.companyId,
  })
  if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
  return NextResponse.json({ ok: true, purchase: result.bundle.purchase, items: result.bundle.items, reused: result.reused })
}

/** Route purchase history for the trip (task §5.4, §7.2). */
export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params
  const guard = await requireCartAccess(id)
  if (!guard.ok) return guard.response
  const purchases = await listTripPurchases(guard.trip.id)
  return NextResponse.json({ ok: true, purchases })
}
