import { NextRequest, NextResponse } from 'next/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { requireParticipant } from '@/lib/api-guard'
import { logTripEvent } from '@/lib/audit'

/** Dismiss (accept) a warning: marks it resolved so it leaves the boards. */

const MANAGE_ROLES = new Set(['broker', 'dispatcher', 'admin'])

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

  if (!MANAGE_ROLES.has(participant.role)) {
    return NextResponse.json(
      { error: 'Only the broker or carrier side can dismiss warnings.' },
      { status: 403 },
    )
  }

  const admin = createAdminClient()
  const { data: warning, error } = await admin
    .from('warnings')
    .update({ resolved: true })
    .eq('id', warningId)
    .eq('trip_id', tripId)
    .select()
    .single()
  if (error || !warning) {
    return NextResponse.json({ error: 'Could not dismiss the warning.' }, { status: 500 })
  }

  await logTripEvent({
    tripId,
    actorId: user.id,
    actorLabel: participant.name || user.email || 'participant',
    action: 'warning_dismissed',
    detail: { message: warning.message },
  })

  return NextResponse.json({ ok: true })
}
