import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { updateRiskScore } from '@/lib/risk-engine';

export async function PATCH(request: NextRequest) {
  try {
    const id = request.url.split('/').filter(Boolean).pop();

    if (!id) {
      return NextResponse.json(
        { success: false, error: 'Report ID is required' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { status, adminId } = body;

    if (!status || !adminId) {
      return NextResponse.json(
        { success: false, error: 'Status and adminId are required' },
        { status: 400 }
      );
    }

    const validStatuses = ['pending', 'verified', 'suspicious', 'rejected'];
    if (!validStatuses.includes(status)) {
      return NextResponse.json(
        { success: false, error: 'Invalid status. Must be: pending, verified, suspicious, or rejected' },
        { status: 400 }
      );
    }

    const existingReport = await db.scamReport.findUnique({
      where: { id },
      include: { linkedEntities: true },
    });

    if (!existingReport) {
      return NextResponse.json(
        { success: false, error: 'Report not found' },
        { status: 404 }
      );
    }

    // Verify admin exists
    const admin = await db.user.findUnique({ where: { id: adminId } });
    if (!admin || admin.role !== 'admin') {
      return NextResponse.json(
        { success: false, error: 'Unauthorized: Admin access required' },
        { status: 401 }
      );
    }

    const updatedReport = await db.scamReport.update({
      where: { id },
      data: {
        status,
        verifiedBy: adminId,
        verifiedAt: new Date(),
        riskLevel: status === 'verified' ? 'high' : status === 'rejected' ? 'low' : existingReport.riskLevel,
      },
      include: {
        reporter: {
          select: { id: true, name: true, email: true },
        },
        category: true,
        evidence: true,
        linkedEntities: true,
      },
    });

    // Determine admin action for log
    let action = 'update_status';
    if (status === 'verified') action = 'approve';
    else if (status === 'rejected') action = 'reject';

    // Create admin log entry
    await db.adminLog.create({
      data: {
        adminId,
        action,
        targetType: 'report',
        targetId: id,
        details: `Report status changed from "${existingReport.status}" to "${status}"`,
      },
    });

    // Update risk scores for all linked entities
    for (const entity of existingReport.linkedEntities) {
      await updateRiskScore(entity.entityType, entity.entityValue);
    }

    return NextResponse.json(
      { success: true, data: updatedReport },
      { status: 200 }
    );
  } catch (error) {
    console.error('Admin update report error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
