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

export async function GET() {
  try {
    // Total reports
    const totalReports = await db.scamReport.count();

    // Total amount lost
    const amountResult = await db.scamReport.aggregate({
      _sum: { amountLost: true },
    });
    const totalAmount = amountResult._sum.amountLost || 0;

    // Verified reports
    const verifiedReports = await db.scamReport.count({
      where: { status: 'verified' },
    });

    // Critical entities
    const criticalEntities = await db.riskScore.count({
      where: { riskLevel: 'critical' },
    });

    // Top 5 categories by report count
    const categories = await db.scamCategory.findMany({
      include: {
        _count: { select: { reports: true } },
      },
      orderBy: { reports: { _count: 'desc' } },
      take: 5,
    });
    const topCategories = categories.map((c) => ({
      name: c.name,
      slug: c.slug,
      count: c._count.reports,
    }));

    // Top 5 districts by report count
    const districtReports = await db.scamReport.findMany({
      where: { district: { not: null } },
      select: { district: true },
    });
    const districtCounts = new Map<string, number>();
    for (const r of districtReports) {
      if (r.district) {
        districtCounts.set(r.district, (districtCounts.get(r.district) || 0) + 1);
      }
    }
    const topDistricts = Array.from(districtCounts.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5)
      .map(([district, count]) => ({ district, count }));

    // Daily trends - last 30 days
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const recentReports = await db.scamReport.findMany({
      where: { createdAt: { gte: thirtyDaysAgo } },
      select: { createdAt: true, amountLost: true },
    });

    const dailyMap = new Map<string, { count: number; amount: number }>();
    for (const r of recentReports) {
      const dateKey = r.createdAt.toISOString().split('T')[0];
      const existing = dailyMap.get(dateKey) || { count: 0, amount: 0 };
      existing.count += 1;
      existing.amount += r.amountLost;
      dailyMap.set(dateKey, existing);
    }
    const dailyTrends = Array.from(dailyMap.entries())
      .sort((a, b) => a[0].localeCompare(b[0]))
      .map(([date, data]) => ({ date, ...data }));

    // Risk distribution
    const riskCounts = await db.riskScore.groupBy({
      by: ['riskLevel'],
      _count: { riskLevel: true },
    });

    const riskDistribution = { low: 0, medium: 0, high: 0, critical: 0 };
    for (const rc of riskCounts) {
      const level = rc.riskLevel as keyof typeof riskDistribution;
      if (level in riskDistribution) {
        riskDistribution[level] = rc._count.riskLevel;
      }
    }

    return NextResponse.json(
      {
        success: true,
        data: {
          totalReports,
          totalAmount,
          verifiedReports,
          criticalEntities,
          topCategories,
          topDistricts,
          dailyTrends,
          riskDistribution,
        },
      },
      { status: 200 }
    );
  } catch (error) {
    console.error('Analytics error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
