import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { runAlertEngineForPorts } from '@/lib/services/alert-engine';

/**
 * Admin trigger for an immediate alert engine sweep over the caller's port.
 * Useful for manual ops ("re-evaluate now after I fixed a rule") and
 * exercised by the realapi socket fanout test.
 *
 * Requires super_admin or per-port admin permissions; the engine itself
 * is idempotent - duplicate runs only re-evaluate, never duplicate rows.
 */
export const POST = withAuth(async (_req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.alerts.run-engine');
    const summary = await runAlertEngineForPorts([ctx.portId]);
    return NextResponse.json({ data: summary });
  } catch (error) {
    return errorResponse(error);
  }
});
