export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { createClient } from '@/lib/supabase/server' import { getSession } from '@/lib/auth/get-session' import { createInAppNotifications } from '@/lib/notifications/in-app' export async function POST( _request: NextRequest, { params }: { params: Promise<{ id: string }> } ) { const { id } = await params const session = await getSession() if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) if (!['hse', 'admin'].includes(session.role)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const supabase = await createClient() const { data: incident } = await supabase .from('incidents') .select('status, reference_no, reported_by') .eq('id', id) .single() if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 }) if (incident.status === 'closed') return NextResponse.json({ error: 'Already closed' }, { status: 409 }) if (incident.status !== 'verification') return NextResponse.json({ error: 'Incident must be in verification status' }, { status: 409 }) const { data: openCapas } = await supabase .from('capa_actions') .select('id') .eq('incident_id', id) .not('status', 'in', '(verified,closed)') if (openCapas && openCapas.length > 0) return NextResponse.json({ error: 'All CAPA actions must be verified before closure' }, { status: 409 }) const closedAt = new Date().toISOString() const { error } = await supabase .from('incidents') .update({ status: 'closed', closed_at: closedAt }) .eq('id', id) if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 }) await supabase.rpc('write_audit_log', { p_table_name: 'incidents', p_record_id: id, p_action: 'closed', p_new_value: { status: 'closed', closed_at: closedAt, closed_by: session.sub }, }) if (incident.reported_by) { await createInAppNotifications([{ userId: incident.reported_by, title: `Your incident report ${incident.reference_no ?? ''} has been closed`, link: '/reporter', incidentId: id, }]) } return NextResponse.json({ ok: true, closed_at: closedAt }) }