/**
 * POST /api/phishing/campaigns/[id]/remediate
 *
 * Executes (simulated, D-01) remediation for whatever was previously approved
 * on this campaign — no request body needed, the action set was fixed at
 * approval time. Gated by phishing/remediate (D-02 — super-admin + admin
 * only). Validates the campaign id as a UUID (V5), then delegates to
 * `remediateApprovedActions` (Plan 01), which is idempotent (REMED-04) and
 * throws explicitly when nothing is approved (REMED-03).
 */

import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
import {
  remediateApprovedActions,
  RemediationValidationError,
  RemediationConflictError,
} from '@/lib/services/remediation-service';

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { session, error } = await requirePermission('phishing', 'remediate');
  if (error) return error;

  const { id } = await params;
  // V5: validate UUID shape before querying — a malformed id would otherwise
  // surface as an unhandled Postgres error -> uncaught 500.
  if (!UUID_RE.test(id)) {
    return NextResponse.json({ error: 'Invalid campaign id' }, { status: 400 });
  }

  const actor = (session?.user as { email?: string } | undefined)?.email ?? null;

  try {
    const campaignRes = await postgresClient.query<{ id: string }>(
      `SELECT id FROM campaigns WHERE id = $1`,
      [id]
    );
    if (!campaignRes.rows[0]) {
      return NextResponse.json({ error: 'Campaign not found' }, { status: 404 });
    }

    const result = await remediateApprovedActions(id, actor);
    return NextResponse.json(result);
  } catch (err) {
    if (err instanceof RemediationValidationError) {
      return NextResponse.json({ error: err.message }, { status: 400 });
    }
    if (err instanceof RemediationConflictError) {
      return NextResponse.json({ error: err.message }, { status: 409 });
    }
    console.error('[PHISHING-REMEDIATE] Failed to remediate approved actions', id, err);
    return NextResponse.json(
      { error: 'Failed to remediate approved actions', message: err instanceof Error ? err.message : 'Unknown error' },
      { status: 500 }
    );
  }
}
