import { NextResponse } from 'next/server';
import { and, eq, isNull, sql } from 'drizzle-orm';

import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { alerts } from '@/lib/db/schema/insights';

export const GET = withAuth(async (_req, ctx) => {
  const rows = await db
    .select({ severity: alerts.severity, count: sql<number>`count(*)::int` })
    .from(alerts)
    .where(
      and(eq(alerts.portId, ctx.portId), isNull(alerts.resolvedAt), isNull(alerts.dismissedAt)),
    )
    .groupBy(alerts.severity);

  const bySeverity = { info: 0, warning: 0, critical: 0 } as Record<string, number>;
  let total = 0;
  for (const r of rows) {
    bySeverity[r.severity] = r.count;
    total += r.count;
  }
  return NextResponse.json({ total, bySeverity });
});
