import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const status = searchParams.get('status');
    const category = searchParams.get('category');
    const sort = searchParams.get('sort') || 'createdAt';
    const search = searchParams.get('search');

    const skip = (page - 1) * limit;

    const where: Record<string, unknown> = {};

    if (status) {
      where.status = status;
    }

    if (category) {
      where.scamType = category;
    }

    if (search) {
      where.OR = [
        { title: { contains: search } },
        { description: { contains: search } },
        { scammerPhone: { contains: search } },
        { bKashNumber: { contains: search } },
        { nagadNumber: { contains: search } },
        { facebookUrl: { contains: search } },
        { sellerName: { contains: search } },
        { district: { contains: search } },
      ];
    }

    const orderBy: Record<string, string> = {};
    if (sort === 'upvotes') {
      orderBy.upvotes = 'desc';
    } else if (sort === 'views') {
      orderBy.views = 'desc';
    } else if (sort === 'amountLost') {
      orderBy.amountLost = 'desc';
    } else {
      orderBy.createdAt = 'desc';
    }

    const [reports, total] = await Promise.all([
      db.scamReport.findMany({
        where,
        skip,
        take: limit,
        orderBy,
        include: {
          reporter: {
            select: { id: true, name: true, email: true },
          },
          category: {
            select: { id: true, name: true, slug: true, icon: true, color: true },
          },
        },
      }),
      db.scamReport.count({ where }),
    ]);

    return NextResponse.json(
      {
        success: true,
        data: {
          reports,
          pagination: {
            page,
            limit,
            total,
            totalPages: Math.ceil(total / limit),
          },
        },
      },
      { status: 200 }
    );
  } catch (error) {
    console.error('List reports error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      title,
      description,
      scamType,
      scammerPhone,
      bKashNumber,
      nagadNumber,
      facebookUrl,
      sellerName,
      amountLost,
      transactionDate,
      contactEmail,
      district,
      reporterId,
      categoryId,
      evidence,
    } = body;

    if (!title || !description || !scamType || !reporterId) {
      return NextResponse.json(
        { success: false, error: 'Title, description, scam type, and reporter ID are required' },
        { status: 400 }
      );
    }

    const reporter = await db.user.findUnique({
      where: { id: reporterId },
    });

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

    if (reporter.banned) {
      return NextResponse.json(
        { success: false, error: 'Your account has been banned and cannot submit reports' },
        { status: 401 }
      );
    }

    // Build linked entities data
    const linkedEntitiesData: { entityType: string; entityValue: string }[] = [];

    if (scammerPhone) {
      linkedEntitiesData.push({ entityType: 'phone', entityValue: scammerPhone });
    }
    if (bKashNumber) {
      linkedEntitiesData.push({ entityType: 'bkash', entityValue: bKashNumber });
    }
    if (nagadNumber) {
      linkedEntitiesData.push({ entityType: 'nagad', entityValue: nagadNumber });
    }
    if (facebookUrl) {
      linkedEntitiesData.push({ entityType: 'facebook', entityValue: facebookUrl });
    }
    if (sellerName) {
      linkedEntitiesData.push({ entityType: 'seller', entityValue: sellerName });
    }

    // Build evidence data
    const evidenceData = evidence
      ? evidence.map((e: { fileType: string; fileUrl: string; fileName: string; fileSize?: number; mimeType?: string }) => ({
          fileType: e.fileType || 'image',
          fileUrl: e.fileUrl,
          fileName: e.fileName,
          fileSize: e.fileSize,
          mimeType: e.mimeType,
        }))
      : [];

    // Find category by slug if not provided directly
    let categoryConnectId = categoryId;
    if (!categoryConnectId && scamType) {
      const categoryBySlug = await db.scamCategory.findUnique({
        where: { slug: scamType },
      });
      if (categoryBySlug) {
        categoryConnectId = categoryBySlug.id;
      }
    }

    const report = await db.scamReport.create({
      data: {
        title,
        description,
        scamType,
        scammerPhone: scammerPhone || null,
        bKashNumber: bKashNumber || null,
        nagadNumber: nagadNumber || null,
        facebookUrl: facebookUrl || null,
        sellerName: sellerName || null,
        amountLost: parseFloat(String(amountLost)) || 0,
        transactionDate: transactionDate ? new Date(transactionDate) : null,
        contactEmail: contactEmail || null,
        district: district || null,
        reporterId,
        categoryId: categoryConnectId || null,
        linkedEntities: {
          create: linkedEntitiesData,
        },
        evidence: {
          create: evidenceData,
        },
      },
      include: {
        reporter: {
          select: { id: true, name: true, email: true },
        },
        category: true,
        evidence: true,
        linkedEntities: true,
      },
    });

    // Update risk scores for all linked entities
    const { updateRiskScore } = await import('@/lib/risk-engine');
    for (const entity of linkedEntitiesData) {
      await updateRiskScore(entity.entityType, entity.entityValue);
    }

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