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';

// The alert feed is entirely operational/deal signals (stale interest, hot lead
// silent, EOI unsigned, signer overdue, reservation needs agreement, berth
// stalled, duplicate/unscanned expense) — there are no audit/security alert
// rules. Gated on interests.view so the operational roles that act on these
// (sales, director, viewer) see them; external residential partners don't.
export const GET = withAuth(
  withPermission('interests', 'view', 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 });
  }),
);
