export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { eq } from 'drizzle-orm' import { getSession } from '@/lib/auth/get-session' import { withUser } from '@/lib/db/with-user' import { writeAuditLog } from '@/lib/db/audit' import { capaActions, evidenceFiles } from '@/lib/db/schema' import { uploadEvidenceFile } from '@/lib/storage/evidence' import { validateCapaSubmission } from '@/lib/capa/submit-validation' 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 }) const [capa] = await withUser(session.sub, async tx => tx.select({ incidentId: capaActions.incidentId, ownerUserId: capaActions.ownerUserId, status: capaActions.status, }).from(capaActions).where(eq(capaActions.id, id)).limit(1) ) if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 }) const isElevated = ['hse', 'admin'].includes(session.role) if (capa.ownerUserId !== session.sub && !isElevated) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (capa.status !== 'in_progress') return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 }) const form = await request.formData() const files = form.getAll('files').filter((f): f is File => f instanceof File) const check = validateCapaSubmission(String(form.get('note') ?? ''), files) if (!check.ok) return NextResponse.json({ error: 'Validation failed', details: check.errors }, { status: 422 }) const uploaded: Array<{ publicUrl: string; hash: string; type: string }> = [] try { for (const file of files) { const { publicUrl, hash } = await uploadEvidenceFile(file, capa.incidentId, 'capa', session.sub) uploaded.push({ publicUrl, hash, type: file.type }) } } catch (err) { return NextResponse.json( { error: 'Photo upload failed', details: [err instanceof Error ? err.message : 'unknown error'] }, { status: 422 }, ) } const completedAt = new Date() await withUser(session.sub, async tx => { const rows = await tx.insert(evidenceFiles).values( uploaded.map(u => ({ incidentId: capa.incidentId, capaId: id, stage: 'capa' as const, fileUrl: u.publicUrl, fileType: u.type, fileHash: u.hash, uploadedBy: session.sub, })) ).returning({ id: evidenceFiles.id }) await tx.update(capaActions).set({ status: 'pending_verification', ownerNotes: check.note, completedAt, }).where(eq(capaActions.id, id)) await writeAuditLog( tx, 'capa_actions', id, 'submitted_for_verification', { status: 'pending_verification', owner_notes: check.note, completed_at: completedAt.toISOString(), evidence_file_ids: rows.map(r => r.id), }, { status: 'in_progress' }, ) }) return NextResponse.json({ ok: true }) }