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 { notificationsLog } from '@/lib/db/schema' import { eq, and, isNull, inArray, desc, sql } from 'drizzle-orm' export async function GET() { const session = await getSession() if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) const notifications = await withUser(session.sub, async tx => tx.select({ id: notificationsLog.id, title: notificationsLog.title, link: notificationsLog.link, incidentId: notificationsLog.incidentId, capaId: notificationsLog.capaId, sentAt: notificationsLog.sentAt, readAt: notificationsLog.readAt, }) .from(notificationsLog) .where(and( eq(notificationsLog.channel, 'in_app'), eq(notificationsLog.recipientUserId, session.sub), )) .orderBy(desc(notificationsLog.sentAt)) .limit(20) ) const [unreadRow] = await withUser(session.sub, async tx => tx.select({ count: sql`count(*)` }) .from(notificationsLog) .where(and( eq(notificationsLog.channel, 'in_app'), eq(notificationsLog.recipientUserId, session.sub), isNull(notificationsLog.readAt), )) ) const unread = Number(unreadRow?.count ?? 0) return NextResponse.json({ notifications: notifications.map(n => ({ id: n.id, title: n.title, link: n.link, incident_id: n.incidentId, capa_id: n.capaId, sent_at: n.sentAt, read_at: n.readAt, })), unread, }) } export async function POST(request: NextRequest) { const session = await getSession() if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) const body: { ids?: string[]; all?: boolean } = await request.json().catch(() => ({})) if (!body.all) { if (!Array.isArray(body.ids) || body.ids.length === 0) return NextResponse.json({ error: 'ids required unless all:true' }, { status: 422 }) } const baseWhere = and( eq(notificationsLog.recipientUserId, session.sub), isNull(notificationsLog.readAt), ) const whereClause = body.all ? baseWhere : and(baseWhere, inArray(notificationsLog.id, body.ids!)) await withUser(session.sub, async tx => tx.update(notificationsLog) .set({ readAt: new Date() }) .where(whereClause) ) return NextResponse.json({ ok: true }) }