import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { requireParticipant } from '@/lib/api-guard'
import { canAssignCarrier } from '@/lib/domain/carrier-assignment'
import { assignTripCarrier, carrierOptionsForViewer } from '@/lib/data/carrier-assignment'

/**
 * The dispatcher (or an admin) chooses which carrier is performing this trip
 * (Nash, 2026-09-19): "if the dispatcher has multiple relations with
 * multiple carriers… on the overview he's going to have to choose which
 * carrier will be performing this trip, and when he makes that selection
 * and applies, this is the relation that will be created."
 *
 * The choice is limited to the caller's own carrier relations — an admin may
 * pick any carrier company. Written to trips.carrier_company_id (+ the
 * display name) and logged as `carrier_assigned`.
 */
const schema = z.object({ company_id: z.string().uuid() })

export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const { id: tripId } = await ctx.params
  const guard = await requireParticipant(tripId)
  if (!guard.ok) return guard.response
  const { user, participant } = guard

  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Choose a carrier.' }, { status: 400 })

  const isAdmin = user.role === 'admin'
  if (!canAssignCarrier({ viewerRole: participant.role, viewerIsAdmin: isAdmin })) {
    return NextResponse.json({ error: 'Only the carrier dispatcher can choose the carrier for this trip.' }, { status: 403 })
  }
  const options = await carrierOptionsForViewer({ id: user.id, role: user.role }, participant.role)
  const carrier = options.find((c) => c.id === parsed.data.company_id)
  if (!carrier) {
    return NextResponse.json({ error: 'That carrier is not one of your companies.' }, { status: 403 })
  }

  await assignTripCarrier({
    tripId,
    carrier,
    actorId: user.id,
    actorLabel: participant.name || user.name || user.email,
    method: 'selected',
    force: true,
  })
  return NextResponse.json({ ok: true, carrier })
}
