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

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const days = parseInt(searchParams.get('days') || '30');
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // Order analytics
    const orders = await prisma.swagOrder.findMany({
      where: {
        createdAt: { gte: startDate },
        paymentStatus: 'paid',
      },
      include: {
        items: {
          include: { product: true, variant: true },
        },
      },
    });

    // Revenue by day
    const revenueByDay: Record<string, number> = {};
    orders.forEach((order: any) => {
      const day = order.createdAt.toISOString().split('T')[0];
      revenueByDay[day] = (revenueByDay[day] || 0) + order.total;
    });

    // Top products
    const productSales: Record<string, { name: string; quantity: number; revenue: number }> = {};
    orders.forEach((order: any) => {
      order.items.forEach((item: any) => {
        const key = item.productId;
        if (!productSales[key]) {
          productSales[key] = { name: item.product.name, quantity: 0, revenue: 0 };
        }
        productSales[key].quantity += item.quantity;
        productSales[key].revenue += item.totalPrice;
      });
    });

    const topProducts = Object.entries(productSales)
      .map(([id, data]) => ({ id, ...data }))
      .sort((a, b) => b.revenue - a.revenue)
      .slice(0, 10);

    // Category breakdown
    const categoryBreakdown: Record<string, { quantity: number; revenue: number }> = {};
    orders.forEach((order: any) => {
      order.items.forEach((item: any) => {
        const category = item.product.category;
        if (!categoryBreakdown[category]) {
          categoryBreakdown[category] = { quantity: 0, revenue: 0 };
        }
        categoryBreakdown[category].quantity += item.quantity;
        categoryBreakdown[category].revenue += item.totalPrice;
      });
    });

    // Summary stats
    const totalRevenue = orders.reduce((sum: number, o: any) => sum + o.total, 0);
    const totalOrders = orders.length;
    const avgOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0;
    const totalItems = orders.reduce((sum: number, o: any) => 
      sum + o.items.reduce((s: number, i: any) => s + i.quantity, 0), 0);

    return NextResponse.json({
      summary: {
        totalRevenue,
        totalOrders,
        avgOrderValue,
        totalItems,
        period: `${days} days`,
      },
      revenueByDay,
      topProducts,
      categoryBreakdown,
    });
  } catch (error) {
    console.error('Error fetching analytics:', error);
    return NextResponse.json({ error: 'Failed to fetch analytics' }, { status: 500 });
  }
}
