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

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

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

// Tier-4 (authz-auditor): alerts include permission_denied + audit-adjacent
// signals. Gated on admin.view_audit_log — same permission the audit log
// page uses.
export const GET = withAuth(
  withPermission('admin', 'view_audit_log', 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 });
  }),
);
