import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const days = parseInt(searchParams.get('days') || '30');

    // Mock data - à remplacer par vrais modèles ML
    const forecast = generateForecastData(days);
    const correlations = [
      { metric1: 'Température', metric2: 'Ventes Boissons', correlation: 0.87, strength: 'Forte positive' },
      { metric1: 'Prix Diesel', metric2: 'Volume Ventes', correlation: -0.72, strength: 'Forte négative' },
      { metric1: 'Weekend', metric2: 'CA Shop', correlation: 0.65, strength: 'Moyenne positive' },
      { metric1: 'Pluie', metric2: 'Transactions', correlation: -0.45, strength: 'Faible négative' },
      { metric1: 'Promotions', metric2: 'Panier Moyen', correlation: 0.58, strength: 'Moyenne positive' },
    ];

    const anomalies = [
      {
        timestamp: new Date(Date.now() - 2 * 3600000).toISOString(),
        metric: 'CA Horaire',
        value: 450,
        expected: 280,
        deviation: 60.7,
        severity: 'HIGH',
      },
      {
        timestamp: new Date(Date.now() - 5 * 3600000).toISOString(),
        metric: 'Volume Diesel',
        value: 120,
        expected: 250,
        deviation: -52.0,
        severity: 'MEDIUM',
      },
      {
        timestamp: new Date(Date.now() - 24 * 3600000).toISOString(),
        metric: 'Tx Shop',
        value: 15,
        expected: 45,
        deviation: -66.7,
        severity: 'HIGH',
      },
    ];

    return NextResponse.json({
      forecast,
      correlations,
      anomalies,
    });
  } catch (error) {
    console.error('Error fetching advanced analytics:', error);
    return NextResponse.json(
      { error: 'Failed to fetch analytics' },
      { status: 500 }
    );
  }
}

function generateForecastData(days: number) {
  const data = [];
  const baseValue = 2500;
  
  for (let i = -days; i <= 7; i++) {
    const date = new Date();
    date.setDate(date.getDate() + i);
    const actual = i <= 0 ? baseValue + Math.random() * 500 - 250 : 0;
    const predicted = baseValue + Math.sin(i / 7) * 300 + Math.random() * 100;
    
    data.push({
      date: date.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit' }),
      actual: actual,
      predicted: predicted,
      confidence: 0.85 + Math.random() * 0.1,
    });
  }
  
  return data;
}
