export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { getSession } from '@/lib/auth/get-session' import { withUser } from '@/lib/db/with-user' import { writeAuditLog } from '@/lib/db/audit' import { incidents, capaActions } from '@/lib/db/schema' import { eq, and, not, inArray } from 'drizzle-orm' 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 [incident] = await withUser(session.sub, async tx => tx.select({ status: incidents.status, referenceNo: incidents.referenceNo, reportedBy: incidents.reportedBy }) .from(incidents).where(eq(incidents.id, id)).limit(1) ) 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 openCapas = await withUser(session.sub, async tx => tx.select({ id: capaActions.id }) .from(capaActions) .where(and( eq(capaActions.incidentId, id), not(inArray(capaActions.status, ['verified', 'closed'])), )) ) if (openCapas.length > 0) return NextResponse.json({ error: 'All CAPA actions must be verified before closure' }, { status: 409 }) const closedAt = new Date() await withUser(session.sub, async tx => { await tx.update(incidents).set({ status: 'closed', closedAt }).where(eq(incidents.id, id)) await writeAuditLog(tx, 'incidents', id, 'closed', { status: 'closed', closed_at: closedAt.toISOString(), closed_by: session.sub, }) }) if (incident.reportedBy) { await createInAppNotifications([{ userId: incident.reportedBy, title: `Your incident report ${incident.referenceNo ?? ''} has been closed`, link: '/reporter', incidentId: id, }]) } return NextResponse.json({ ok: true, closed_at: closedAt.toISOString() }) }