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

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const query = searchParams.get('q')?.trim();

    if (!query) {
      return NextResponse.json(
        { success: false, error: 'Please provide a number or identifier to check' },
        { status: 400 }
      );
    }

    // Detect the type of input
    const inputType = detectInputType(query);

    // Search across all entity types
    const entityResults = await db.linkedEntity.findMany({
      where: {
        entityValue: { contains: query },
      },
      include: {
        report: {
          select: {
            id: true,
            title: true,
            status: true,
            riskLevel: true,
            riskScore: true,
            amountLost: true,
            createdAt: true,
            scamType: true,
            district: true,
          },
        },
      },
      take: 20,
    });

    // Get risk score if available
    const riskScore = await db.riskScore.findFirst({
      where: {
        entityType: inputType.type,
        entityValue: query,
      },
    });

    // Also try a broader match on risk scores
    const broaderRiskScores = await db.riskScore.findMany({
      where: {
        entityValue: { contains: query },
      },
      take: 5,
    });

    // Group by entity value to avoid duplicates
    const entityMap = new Map<string, {
      entityType: string;
      entityValue: string;
      reportCount: number;
      reports: typeof entityResults[number]['report'][];
    }>();

    for (const entity of entityResults) {
      const key = `${entity.entityType}:${entity.entityValue}`;
      if (!entityMap.has(key)) {
        entityMap.set(key, {
          entityType: entity.entityType,
          entityValue: entity.entityValue,
          reportCount: 0,
          reports: [],
        });
      }
      const entry = entityMap.get(key)!;
      entry.reportCount++;
      entry.reports.push(entity.report);
    }

    // Get total report count for this query
    const totalReports = await db.scamReport.count({
      where: {
        OR: [
          { scammerPhone: { contains: query } },
          { bKashNumber: { contains: query } },
          { nagadNumber: { contains: query } },
          { facebookUrl: { contains: query } },
          { sellerName: { contains: query } },
          { contactEmail: { contains: query } },
        ],
      },
    });

    // Calculate total amount lost
    const amountLostResult = await db.scamReport.aggregate({
      _sum: { amountLost: true },
      where: {
        OR: [
          { scammerPhone: { contains: query } },
          { bKashNumber: { contains: query } },
          { nagadNumber: { contains: query } },
          { facebookUrl: { contains: query } },
          { sellerName: { contains: query } },
          { contactEmail: { contains: query } },
        ],
      },
    });

    const totalAmountLost = amountLostResult._sum.amountLost || 0;

    // Determine overall risk assessment
    const riskAssessment = calculateOverallRisk(totalReports, riskScore, entityResults.length);

    // Build recent reports list
    const recentReports = await db.scamReport.findMany({
      where: {
        OR: [
          { scammerPhone: { contains: query } },
          { bKashNumber: { contains: query } },
          { nagadNumber: { contains: query } },
          { facebookUrl: { contains: query } },
          { sellerName: { contains: query } },
        ],
      },
      select: {
        id: true,
        title: true,
        status: true,
        riskLevel: true,
        riskScore: true,
        amountLost: true,
        createdAt: true,
        scamType: true,
        district: true,
        upvotes: true,
      },
      orderBy: { createdAt: 'desc' },
      take: 5,
    });

    return NextResponse.json({
      success: true,
      data: {
        query,
        inputType,
        riskAssessment,
        stats: {
          totalReports,
          totalAmountLost,
          uniqueEntities: entityMap.size,
        },
        riskScore: riskScore || (broaderRiskScores.length > 0 ? broaderRiskScores[0] : null),
        matchedEntities: Array.from(entityMap.values()),
        recentReports,
        recommendations: generateRecommendations(inputType, totalReports, riskAssessment.level),
      },
    });
  } catch (error) {
    console.error('Check number error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}

function detectInputType(input: string): { type: string; label: string; icon: string } {
  // BD phone number patterns
  const bdPhoneRegex = /^(\+880|880|0)1[3-9]\d{8}$/;
  const partialPhoneRegex = /^01[3-9]\d{0,8}$/;

  if (bdPhoneRegex.test(input) || partialPhoneRegex.test(input)) {
    // Check if it might be a bKash/Nagad number (BD numbers can be both)
    return { type: 'phone', label: 'Phone Number', icon: 'Phone' };
  }

  if (input.includes('facebook.com') || input.includes('fb.com') || input.includes('fb.me')) {
    return { type: 'facebook', label: 'Facebook Profile/Page', icon: 'Facebook' };
  }

  if (input.includes('@') && input.includes('.')) {
    return { type: 'email', label: 'Email Address', icon: 'Mail' };
  }

  // Check if it looks like a bKash/Nagad specific mention
  const lowerInput = input.toLowerCase();
  if (lowerInput.includes('bkash') || lowerInput.includes('b-kash')) {
    return { type: 'bkash', label: 'bKash Number', icon: 'Wallet' };
  }
  if (lowerInput.includes('nagad')) {
    return { type: 'nagad', label: 'Nagad Number', icon: 'Wallet' };
  }

  // Default: general search
  return { type: 'general', label: 'Search Query', icon: 'Search' };
}

function calculateOverallRisk(
  reportCount: number,
  riskScore: { riskLevel: string; score: number } | null,
  entityMatchCount: number
): { level: 'safe' | 'low' | 'medium' | 'high' | 'critical'; score: number; description: string } {
  // If we have a stored risk score, use it
  if (riskScore) {
    const level = riskScore.riskLevel as 'low' | 'medium' | 'high' | 'critical';
    return {
      level,
      score: riskScore.score,
      description: getRiskDescription(level, reportCount),
    };
  }

  // Calculate from report count
  let score = 0;
  if (reportCount >= 10) score = 90;
  else if (reportCount >= 5) score = 70;
  else if (reportCount >= 3) score = 55;
  else if (reportCount >= 2) score = 40;
  else if (reportCount >= 1) score = 25;
  else score = 0; // No reports = potentially safe

  const level: 'safe' | 'low' | 'medium' | 'high' | 'critical' =
    score >= 75 ? 'critical' :
    score >= 50 ? 'high' :
    score >= 30 ? 'medium' :
    score >= 10 ? 'low' :
    'safe';

  return {
    level,
    score,
    description: getRiskDescription(level, reportCount),
  };
}

function getRiskDescription(level: string, reportCount: number): string {
  switch (level) {
    case 'critical':
      return `⚠️ DANGER: This number has been reported ${reportCount} times with multiple verified scams. Do NOT send money or share personal information.`;
    case 'high':
      return `🔴 HIGH RISK: This number has ${reportCount} scam reports. Multiple people have lost money. Exercise extreme caution.`;
    case 'medium':
      return `🟡 MODERATE RISK: This number has ${reportCount} report(s). Some suspicious activity has been flagged. Proceed with caution.`;
    case 'low':
      return `🟢 LOW RISK: This number has only ${reportCount} report(s). No verified scams yet, but stay alert.`;
    case 'safe':
    default:
      return `✅ NO REPORTS FOUND: This number has not been reported on ScamChecker BD yet. However, always stay cautious — scammers frequently change numbers.`;
  }
}

function generateRecommendations(
  inputType: { type: string; label: string },
  reportCount: number,
  riskLevel: string
): string[] {
  const recommendations: string[] = [];

  if (riskLevel === 'critical' || riskLevel === 'high') {
    recommendations.push('🚫 Do NOT send money via bKash, Nagad, or any other method to this number');
    recommendations.push('📞 Contact your bank/mobile financial service to block transactions if you already sent money');
    recommendations.push('📝 File a report with Bangladesh Cyber Crime division at cybercrime.gov.bd');
  }

  if (riskLevel === 'medium') {
    recommendations.push('🔍 Verify the seller/buyer through multiple channels before any transaction');
    recommendations.push('💳 Never pay full amount in advance — use cash on delivery when possible');
  }

  if (inputType.type === 'phone') {
    recommendations.push('📱 Search this number on Truecaller to check spam reports');
    recommendations.push('💬 Ask the person to video call to verify their identity');
  }

  if (inputType.type === 'facebook') {
    recommendations.push('👤 Check the Facebook profile age and activity — new profiles are often fake');
    recommendations.push('🖼️ Reverse image search profile pictures to check for stolen photos');
  }

  if (reportCount === 0) {
    recommendations.push('✋ Even if a number is not reported yet, always verify before sending money');
    recommendations.push('📢 If you encounter a scam with this number, report it to help others');
  }

  recommendations.push('🔒 Never share OTP, PIN, or personal information with unknown contacts');

  return recommendations;
}
