import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { requireParticipant } from '@/lib/api-guard'
import { logTripEvent } from '@/lib/audit'
import { canEditPermitCost, canSeePermitCost } from '@/lib/domain/permit-cost'
import { correctPermitCost } from '@/lib/data/permit-cost'

/**
 * Correct the state permit fee on one permit (Nash, 2026-09-24, §4):
 * "authorized users should be able to correct the extracted permit cost… if
 * someone manually updates the value, preserve the original extracted amount
 * for audit."
 *
 * The broker or dispatcher on the trip, and internal staff. A driver reads the
 * fee but never changes it; a pilot cannot even see it.
 */
const schema = z.object({
  /** null clears the fee back to "not found". */
  amount: z.number().min(0).max(1_000_000).nullable(),
  reason: z.string().trim().max(300).optional(),
  /** False for a revision that carried no new state charge (§11). */
  counts_toward_total: z.boolean().optional(),
})

export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string; permitId: string }> }) {
  const { id: tripId, permitId } = await ctx.params
  const guard = await requireParticipant(tripId)
  if (!guard.ok) return guard.response
  const { user, participant } = guard
  const isInternal = user.role === 'admin'
  if (!canSeePermitCost(participant.role) || !canEditPermitCost({ role: participant.role, isInternal })) {
    return NextResponse.json({ error: 'You cannot change the permit fee on this trip.' }, { status: 403 })
  }
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Enter a valid amount.' }, { status: 400 })
  const input = parsed.data
  const label = participant.name || user.name || user.email

  const r = await correctPermitCost({
    permitId, tripId, amount: input.amount === null ? null : Math.round(input.amount * 100) / 100,
    reason: input.reason ?? null, actor: { id: user.id, label }, countsTowardTotal: input.counts_toward_total,
  })
  if (!r.ok) return NextResponse.json({ error: r.error }, { status: 400 })
  await logTripEvent({
    tripId, actorId: user.id, actorLabel: label, action: 'permit_cost_corrected',
    detail: { permit_id: permitId, amount: input.amount, status: r.status, reason: input.reason ?? null, counts_toward_total: input.counts_toward_total },
  })
  return NextResponse.json({ ok: true, status: r.status })
}
