import { NextRequest, NextResponse } from 'next/server';
import connectDB from '@/lib/mongodb';
import { PumpTransaction } from '@/models';
import { startOfDay, endOfDay, subDays } from 'date-fns';

/**
 * GET /api/dashboard/overview
 * Retourne les KPIs principaux pour le dashboard
 */
export async function GET(request: NextRequest) {
  try {
    await connectDB();

    const { searchParams } = new URL(request.url);
    const days = parseInt(searchParams.get('days') || '30');
    
    const endDate = new Date();
    const startDate = subDays(endDate, days);

    // KPIs Carburant
    const fuelStats = await PumpTransaction.aggregate([
      {
        $match: {
          txDatetime: {
            $gte: startDate,
            $lte: endDate,
          },
        },
      },
      {
        $group: {
          _id: null,
          totalTransactions: { $sum: 1 },
          totalLiters: { $sum: '$liters' },
          totalRevenue: { $sum: '$totalAmount' },
          avgLitersPerTx: { $avg: '$liters' },
          avgRevenuePerTx: { $avg: '$totalAmount' },
        },
      },
    ]);

    // Ventes par carburant
    const salesByFuel = await PumpTransaction.aggregate([
      {
        $match: {
          txDatetime: {
            $gte: startDate,
            $lte: endDate,
          },
        },
      },
      {
        $group: {
          _id: '$fuelType',
          totalLiters: { $sum: '$liters' },
          totalRevenue: { $sum: '$totalAmount' },
          transactionCount: { $sum: 1 },
          avgPrice: { $avg: '$unitPrice' },
        },
      },
      {
        $sort: { totalRevenue: -1 },
      },
    ]);

    // Tendance journalière (7 derniers jours)
    const dailyTrend = await PumpTransaction.aggregate([
      {
        $match: {
          txDatetime: {
            $gte: subDays(endDate, 7),
            $lte: endDate,
          },
        },
      },
      {
        $group: {
          _id: {
            $dateToString: { format: '%Y-%m-%d', date: '$txDatetime' },
          },
          totalRevenue: { $sum: '$totalAmount' },
          totalLiters: { $sum: '$liters' },
          transactionCount: { $sum: 1 },
        },
      },
      {
        $sort: { _id: 1 },
      },
    ]);

    // Répartition par mode de paiement
    const paymentMethods = await PumpTransaction.aggregate([
      {
        $match: {
          txDatetime: {
            $gte: startDate,
            $lte: endDate,
          },
        },
      },
      {
        $group: {
          _id: '$paymentMethod',
          count: { $sum: 1 },
          totalAmount: { $sum: '$totalAmount' },
        },
      },
    ]);

    return NextResponse.json({
      success: true,
      data: {
        overview: fuelStats[0] || {
          totalTransactions: 0,
          totalLiters: 0,
          totalRevenue: 0,
          avgLitersPerTx: 0,
          avgRevenuePerTx: 0,
        },
        salesByFuel,
        dailyTrend,
        paymentMethods,
        period: {
          startDate,
          endDate,
          days,
        },
      },
    });
  } catch (error) {
    console.error('Erreur API Dashboard:', error);
    return NextResponse.json(
      {
        success: false,
        error: 'Erreur lors de la récupération des données',
      },
      { status: 500 }
    );
  }
}
