import { NextRequest, NextResponse } from 'next/server';

import { withAuth } from '@/lib/api/helpers';
import { listAlertsForPort } from '@/lib/services/alerts.service';

type AlertStatus = 'open' | 'dismissed' | 'resolved';

export const GET = withAuth(async (req: NextRequest, ctx) => {
  const url = new URL(req.url);
  const status = (url.searchParams.get('status') ?? 'open') as AlertStatus;

  const rows = await listAlertsForPort(ctx.portId, {
    includeDismissed: status !== 'open',
    includeResolved: status !== 'open',
  });

  // Filter to the requested status bucket so callers don't see overlap.
  const filtered = rows.filter((a) => {
    if (status === 'open') return !a.dismissedAt && !a.resolvedAt;
    if (status === 'dismissed') return Boolean(a.dismissedAt) && !a.resolvedAt;
    if (status === 'resolved') return Boolean(a.resolvedAt);
    return true;
  });

  return NextResponse.json({ data: filtered });
});
