export const dynamic = 'force-dynamic' import { NextRequest, NextResponse } from 'next/server' import { getSession } from '@/lib/auth/get-session' import { withUser, asAdmin } from '@/lib/db/with-user' import { writeAuditLog } from '@/lib/db/audit' import { incidents, auditLog } from '@/lib/db/schema' import { eq, and, gte, sql } from 'drizzle-orm' import { createDeepSeekClient } from '@/lib/claude/client' import { getApiKey } from '@/lib/settings' 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 }) // Rate limit const since = new Date(Date.now() - 60_000) const [rateRow] = await asAdmin(db => db.select({ cnt: sql`count(*)` }).from(auditLog) .where(and( eq(auditLog.changedBy, session.sub), eq(auditLog.action, 'ai_triage_suggest'), gte(auditLog.changedAt, since), )) ) if (Number(rateRow?.cnt ?? 0) > 0) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) const deepseekKey = await getApiKey('DEEPSEEK_API_KEY') const client = createDeepSeekClient(deepseekKey) const [incident] = await withUser(session.sub, async tx => tx.select({ incidentType: incidents.incidentType, description: incidents.description, injuryInvolved: incidents.injuryInvolved, assetInvolved: incidents.assetInvolved, medicalStatus: incidents.medicalStatus, }) .from(incidents).where(eq(incidents.id, id)).limit(1) ) if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 }) let res: Awaited> try { res = await client.chat.completions.create({ model: 'deepseek-v4-pro', max_tokens: 1024, messages: [ { role: 'system', content: `You are an HSE triage specialist for a Malaysian 3PL warehouse. Assess incidents under NADOPOD 2004. You must respond with valid JSON only — no markdown, no explanation outside the JSON object. Output exactly this JSON structure: { "severity": , "is_fatality": , "is_serious_bodily_injury": , "is_dangerous_occurrence": , "is_occupational_disease": , "rationale": "" }`, }, { role: 'user', content: `Assess this incident under NADOPOD 2004. Respond with JSON only.\n\nIncident type: ${incident.incidentType}\nDescription: ${incident.description}\nInjury involved: ${incident.injuryInvolved ? 'yes' : 'no'}\nMedical status: ${incident.medicalStatus ?? 'N/A'}\nAsset/equipment involved: ${incident.assetInvolved ? 'yes' : 'no'}`, }, ], }) } catch { return NextResponse.json({ error: 'AI service unavailable' }, { status: 503 }) } const raw = res.choices[0]?.message?.content if (!raw) return NextResponse.json({ error: 'AI returned empty response' }, { status: 500 }) const json = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim() let input: { severity?: unknown is_fatality?: unknown is_serious_bodily_injury?: unknown is_dangerous_occurrence?: unknown is_occupational_disease?: unknown rationale?: unknown } try { input = JSON.parse(json) } catch { return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 }) } if ( typeof input.severity !== 'number' || typeof input.is_fatality !== 'boolean' || typeof input.is_serious_bodily_injury !== 'boolean' || typeof input.is_dangerous_occurrence !== 'boolean' || typeof input.is_occupational_disease !== 'boolean' || typeof input.rationale !== 'string' ) { return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 }) } await withUser(session.sub, async tx => { await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'deepseek-v4-pro' }) }) return NextResponse.json(input) }