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

export async function GET() {
  try {
    const orders = await prisma.order.findMany({
      include: {
        lines: {
          include: {
            product: true,
            farm: true
          }
        },
        billingCustomer: true
      }
    });

    let totalRevenue = 0;
    let totalBoxes = 0;
    const revenueByCustomer: Record<string, { name: string; total: number; boxes: number }> = {};
    const revenueByFarm: Record<string, { name: string; total: number; boxes: number }> = {};
    const revenueByProduct: Record<string, { name: string; total: number; boxes: number }> = {};
    const ordersByDay: Record<string, number> = {};

    orders.forEach((order: any) => {
      const day = new Date(order.creationDate).toISOString().split('T')[0];
      ordersByDay[day] = (ordersByDay[day] || 0) + 1;

      order.lines.forEach((line: any) => {
        const lineRevenue = line.quantity * line.price;
        totalRevenue += lineRevenue;
        totalBoxes += line.quantity;

        // By Customer
        if (order.billingCustomer) {
          const cId = order.billingCustomer.id;
          if (!revenueByCustomer[cId]) {
            revenueByCustomer[cId] = { name: order.billingCustomer.businessName, total: 0, boxes: 0 };
          }
          revenueByCustomer[cId].total += lineRevenue;
          revenueByCustomer[cId].boxes += line.quantity;
        }

        // By Farm
        if (line.farm) {
          const fId = line.farm.id;
          if (!revenueByFarm[fId]) {
            revenueByFarm[fId] = { name: line.farm.name, total: 0, boxes: 0 };
          }
          revenueByFarm[fId].total += lineRevenue;
          revenueByFarm[fId].boxes += line.quantity;
        }

        // By Product
        if (line.product) {
          const pId = line.product.id;
          if (!revenueByProduct[pId]) {
            revenueByProduct[pId] = { name: line.product.name, total: 0, boxes: 0 };
          }
          revenueByProduct[pId].total += lineRevenue;
          revenueByProduct[pId].boxes += line.quantity;
        }
      });
    });

    const topCustomers = Object.values(revenueByCustomer).sort((a, b) => b.total - a.total).slice(0, 5);
    const topFarms = Object.values(revenueByFarm).sort((a, b) => b.boxes - a.boxes).slice(0, 5);
    const topProducts = Object.values(revenueByProduct).sort((a, b) => b.boxes - a.boxes).slice(0, 5);
    
    // Sort orders by day for chart
    const chartData = Object.entries(ordersByDay).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));

    return NextResponse.json({
      totalOrders: orders.length,
      totalRevenue,
      totalBoxes,
      topCustomers,
      topFarms,
      topProducts,
      chartData
    });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
