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
 * Returns Sentinel dashboard stats (last scan, open findings, threat DB info)
 */
export async function GET() {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const stats = await dfSentinel.getDashboardStats();
    return NextResponse.json(stats);
  } catch (error) {
    console.error('[Sentinel] Dashboard stats error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch sentinel stats' },
      { status: 500 }
    );
  }
}

/**
 * POST /api/dark-factory/sentinel
 * Trigger a new OWASP scan
 */
export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const { target, targetModule, artifacts } = body;

    const result = await dfSentinel.runScan({
      target: target || 'all',
      targetModule,
      scheduledBy: session.user.email || 'user',
      artifacts: artifacts || [],
    });

    return NextResponse.json(result);
  } catch (error) {
    console.error('[Sentinel] Scan error:', error);
    return NextResponse.json(
      { error: 'Scan failed' },
      { status: 500 }
    );
  }
}
