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 q = searchParams.get('q');

    if (!q || q.trim().length === 0) {
      return NextResponse.json(
        { success: false, error: 'Search query is required' },
        { status: 400 }
      );
    }

    const query = q.trim();

    // Search in linked entities
    const linkedEntities = await db.linkedEntity.findMany({
      where: {
        entityValue: { contains: query },
      },
      include: {
        report: {
          include: {
            reporter: {
              select: { id: true, name: true, email: true },
            },
            category: {
              select: { id: true, name: true, slug: true, icon: true, color: true },
            },
          },
        },
      },
      take: 50,
    });

    // Search in risk scores
    const riskScores = await db.riskScore.findMany({
      where: {
        entityValue: { contains: query },
      },
    });

    // Search directly in report fields
    const directReports = await db.scamReport.findMany({
      where: {
        OR: [
          { scammerPhone: { contains: query } },
          { bKashNumber: { contains: query } },
          { nagadNumber: { contains: query } },
          { facebookUrl: { contains: query } },
          { sellerName: { contains: query } },
        ],
      },
      include: {
        reporter: {
          select: { id: true, name: true, email: true },
        },
        category: {
          select: { id: true, name: true, slug: true, icon: true, color: true },
        },
      },
      take: 50,
    });

    // Group results by entity
    const entityMap = new Map<string, {
      entityValue: string;
      entityType: string;
      riskLevel: string;
      riskScore: number;
      reportCount: number;
      evidenceCount: number;
      lastReported: string | null;
      relatedReports: typeof directReports;
    }>();

    // Process linked entity results
    for (const le of linkedEntities) {
      const key = `${le.entityType}:${le.entityValue}`;
      if (!entityMap.has(key)) {
        const risk = riskScores.find(
          (r) => r.entityType === le.entityType && r.entityValue === le.entityValue
        );
        entityMap.set(key, {
          entityValue: le.entityValue,
          entityType: le.entityType,
          riskLevel: risk?.riskLevel || 'low',
          riskScore: risk?.score || 0,
          reportCount: risk?.reportCount || 0,
          evidenceCount: risk?.evidenceCount || 0,
          lastReported: risk?.lastReported?.toISOString() || null,
          relatedReports: [],
        });
      }
      const entry = entityMap.get(key)!;
      // Avoid duplicate reports
      if (!entry.relatedReports.find((r) => r.id === le.report.id)) {
        entry.relatedReports.push(le.report);
      }
    }

    // Process direct report results - add them to entity groups
    for (const report of directReports) {
      const entities: { type: string; value: string | null }[] = [
        { type: 'phone', value: report.scammerPhone },
        { type: 'bkash', value: report.bKashNumber },
        { type: 'nagad', value: report.nagadNumber },
        { type: 'facebook', value: report.facebookUrl },
        { type: 'seller', value: report.sellerName },
      ];

      for (const entity of entities) {
        if (entity.value && entity.value.toLowerCase().includes(query.toLowerCase())) {
          const key = `${entity.type}:${entity.value}`;
          if (!entityMap.has(key)) {
            const risk = riskScores.find(
              (r) => r.entityType === entity.type && r.entityValue === entity.value
            );
            entityMap.set(key, {
              entityValue: entity.value,
              entityType: entity.type,
              riskLevel: risk?.riskLevel || 'low',
              riskScore: risk?.score || 0,
              reportCount: risk?.reportCount || 0,
              evidenceCount: risk?.evidenceCount || 0,
              lastReported: risk?.lastReported?.toISOString() || null,
              relatedReports: [],
            });
          }
          const entry = entityMap.get(key)!;
          if (!entry.relatedReports.find((r) => r.id === report.id)) {
            entry.relatedReports.push(report);
          }
        }
      }
    }

    // Also add risk scores that weren't found through linked entities or direct reports
    for (const risk of riskScores) {
      const key = `${risk.entityType}:${risk.entityValue}`;
      if (!entityMap.has(key)) {
        entityMap.set(key, {
          entityValue: risk.entityValue,
          entityType: risk.entityType,
          riskLevel: risk.riskLevel,
          riskScore: risk.score,
          reportCount: risk.reportCount,
          evidenceCount: risk.evidenceCount,
          lastReported: risk.lastReported?.toISOString() || null,
          relatedReports: [],
        });
      }
    }

    const results = Array.from(entityMap.values());

    return NextResponse.json(
      { success: true, data: { query, results, totalResults: results.length } },
      { status: 200 }
    );
  } catch (error) {
    console.error('Search error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
