import { NextRequest, NextResponse } from 'next/server';
import connectDB from '@/lib/mongodb';
import { Pump, PumpTransaction } from '@/models';
import { subDays } from 'date-fns';

/**
 * GET /api/pumps/performance
 * Performance par pompe
 */
export async function GET(request: NextRequest) {
  try {
    await connectDB();

    const { searchParams } = new URL(request.url);
    const days = parseInt(searchParams.get('days') || '7');
    
    const endDate = new Date();
    const startDate = subDays(endDate, days);

    const pumps = await Pump.find({ active: true }).lean();

    const pumpPerformance = await Promise.all(
      pumps.map(async (pump) => {
        const stats = await PumpTransaction.aggregate([
          {
            $match: {
              pumpId: pump._id,
              txDatetime: { $gte: startDate, $lte: endDate },
            },
          },
          {
            $group: {
              _id: '$fuelType',
              transactionCount: { $sum: 1 },
              totalLiters: { $sum: '$liters' },
              totalRevenue: { $sum: '$totalAmount' },
              avgLitersPerTx: { $avg: '$liters' },
            },
          },
        ]);

        const totalTransactions = stats.reduce((sum, s) => sum + s.transactionCount, 0);
        const totalRevenue = stats.reduce((sum, s) => sum + s.totalRevenue, 0);
        const totalLiters = stats.reduce((sum, s) => sum + s.totalLiters, 0);

        return {
          pumpId: pump._id,
          pumpCode: pump.pumpCode,
          location: pump.location,
          pumpType: pump.pumpType,
          totalTransactions,
          totalLiters: Math.round(totalLiters),
          totalRevenue: Math.round(totalRevenue * 100) / 100,
          avgRevenuePerDay: Math.round((totalRevenue / days) * 100) / 100,
          fuelTypeBreakdown: stats,
        };
      })
    );

    return NextResponse.json({
      success: true,
      data: pumpPerformance.sort((a, b) => b.totalRevenue - a.totalRevenue),
    });
  } catch (error) {
    console.error('Erreur API Pumps Performance:', error);
    return NextResponse.json(
      { success: false, error: 'Erreur lors de la récupération des performances' },
      { status: 500 }
    );
  }
}
