export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { dfSentinel } from '@/lib/dark-factory/sentinel/service';

/**
 * GET /api/dark-factory/sentinel/findings?scanId=xxx&severity=critical
 * Returns findings for a specific scan
 */
export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const scanId = searchParams.get('scanId');
    const severity = searchParams.get('severity') || undefined;

    if (!scanId) {
      return NextResponse.json({ error: 'scanId is required' }, { status: 400 });
    }

    const findings = await dfSentinel.getScanFindings(scanId, severity);
    return NextResponse.json(findings);
  } catch (error) {
    console.error('[Sentinel] Findings error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch findings' },
      { status: 500 }
    );
  }
}

/**
 * PATCH /api/dark-factory/sentinel/findings
 * Update a finding status (remediate or mark as false positive)
 */
export async function PATCH(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { findingId, action } = await req.json();

    if (!findingId || !action) {
      return NextResponse.json(
        { error: 'findingId and action are required' },
        { status: 400 }
      );
    }

    const user = session.user.email || 'user';

    if (action === 'remediate') {
      const result = await dfSentinel.remediateFinding(findingId, user);
      return NextResponse.json(result);
    } else if (action === 'false_positive') {
      const result = await dfSentinel.markFalsePositive(findingId, user);
      return NextResponse.json(result);
    }

    return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
  } catch (error) {
    console.error('[Sentinel] Finding update error:', error);
    return NextResponse.json(
      { error: 'Failed to update finding' },
      { status: 500 }
    );
  }
}
