export const dynamic = 'force-dynamic' import { NextResponse } from 'next/server' import { getSession } from '@/lib/auth/get-session' import { withUser } from '@/lib/db/with-user' import { incidents, sites } from '@/lib/db/schema' import { eq } from 'drizzle-orm' export async function GET() { const session = await getSession() if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) if (!['hse', 'admin', 'management'].includes(session.role)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const rows = await withUser(session.sub, async tx => tx.select({ id: incidents.id, status: incidents.status, incidentType: incidents.incidentType, siteName: sites.name, }) .from(incidents) .leftJoin(sites, eq(incidents.siteId, sites.id)) .limit(10000) ) const total = rows.length const closed = rows.filter(r => r.status === 'closed').length const open = total - closed const by_type: Record = {} for (const r of rows) { by_type[r.incidentType] = (by_type[r.incidentType] ?? 0) + 1 } const siteMap: Record = {} for (const r of rows) { const name = r.siteName ?? 'Unknown' siteMap[name] = (siteMap[name] ?? 0) + 1 } const by_site = Object.entries(siteMap).map(([name, count]) => ({ name, count })) .sort((a, b) => b.count - a.count) return NextResponse.json({ total, open, closed, by_type, by_site }) }