import { NextResponse } from 'next/server';
import dbConnect from '@/lib/mongodb';
import { POSTransaction } from '@/models';

export async function GET(request: Request) {
  try {
    await dbConnect();

    const { searchParams } = new URL(request.url);
    const days = parseInt(searchParams.get('days') || '30');

    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // Statistiques globales
    const overviewStats = await POSTransaction.aggregate([
      {
        $match: {
          tx_datetime: { $gte: startDate },
        },
      },
      {
        $group: {
          _id: null,
          totalRevenue: { $sum: '$total_amount' },
          transactions: { $sum: 1 },
          avgBasket: { $avg: '$total_amount' },
          itemsSold: { $sum: '$items_count' },
          loyaltyTransactions: {
            $sum: { $cond: [{ $ne: ['$customer_id', null] }, 1, 0] },
          },
        },
      },
    ]);

    const overview = overviewStats[0] || {
      totalRevenue: 0,
      transactions: 0,
      avgBasket: 0,
      itemsSold: 0,
      loyaltyTransactions: 0,
    };

    overview.avgItemsPerBasket = overview.transactions > 0 
      ? overview.itemsSold / overview.transactions 
      : 0;
    
    overview.loyaltyRate = overview.transactions > 0 
      ? (overview.loyaltyTransactions / overview.transactions) * 100 
      : 0;

    // Top 20 produits (mock - nécessite collection pos_tx_items)
    const topProducts = [
      {
        productCode: 'SHOP_SANDWICH_1',
        productName: 'Sandwich Jambon',
        category: 'SHOP_FOOD',
        subCategory: 'SANDWICH',
        quantity: 450,
        revenue: 990.0,
        transactions: 445,
        avgPrice: 2.2,
        margin: 450.0,
        penetration: 35.2,
      },
      {
        productCode: 'SHOP_COFFEE_L',
        productName: 'Café Grand',
        category: 'SHOP_BEVERAGE',
        subCategory: 'HOT',
        quantity: 380,
        revenue: 152.0,
        transactions: 370,
        avgPrice: 0.4,
        margin: 120.0,
        penetration: 29.3,
      },
      {
        productCode: 'SHOP_CHIPS_1',
        productName: 'Chips Nature 150g',
        category: 'SHOP_FOOD',
        subCategory: 'SNACKS',
        quantity: 320,
        revenue: 384.0,
        transactions: 310,
        avgPrice: 1.2,
        margin: 180.0,
        penetration: 24.5,
      },
      {
        productCode: 'SHOP_WATER',
        productName: 'Eau Minérale 50cl',
        category: 'SHOP_BEVERAGE',
        subCategory: 'COLD',
        quantity: 580,
        revenue: 348.0,
        transactions: 550,
        avgPrice: 0.6,
        margin: 220.0,
        penetration: 43.5,
      },
      {
        productCode: 'SHOP_CHOCOLATE',
        productName: 'Barre Chocolat',
        category: 'SHOP_FOOD',
        subCategory: 'CANDY',
        quantity: 290,
        revenue: 174.0,
        transactions: 285,
        avgPrice: 0.6,
        margin: 95.0,
        penetration: 22.5,
      },
    ];

    // Statistiques par catégorie
    const categoryStats = [
      {
        category: 'SHOP_FOOD',
        subCategory: 'SANDWICH',
        quantity: 450,
        revenue: 990.0,
        transactions: 445,
        revenueShare: 31.2,
      },
      {
        category: 'SHOP_BEVERAGE',
        subCategory: 'HOT',
        quantity: 580,
        revenue: 232.0,
        transactions: 560,
        revenueShare: 22.5,
      },
      {
        category: 'SHOP_FOOD',
        subCategory: 'SNACKS',
        quantity: 320,
        revenue: 384.0,
        transactions: 310,
        revenueShare: 18.8,
      },
      {
        category: 'SHOP_BEVERAGE',
        subCategory: 'COLD',
        quantity: 680,
        revenue: 544.0,
        transactions: 650,
        revenueShare: 17.2,
      },
      {
        category: 'SHOP_FOOD',
        subCategory: 'CANDY',
        quantity: 290,
        revenue: 174.0,
        transactions: 285,
        revenueShare: 10.3,
      },
    ];

    return NextResponse.json({
      overview,
      topProducts,
      categoryStats,
    });
  } catch (error) {
    console.error('Error fetching shop performance:', error);
    return NextResponse.json(
      { error: 'Failed to fetch shop performance' },
      { status: 500 }
    );
  }
}
