import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseAdmin } from '@/lib/supabase';
import { Supplier } from '@/types';

export async function POST(req: NextRequest) {
  try {
    const { analysis_id } = await req.json();

    if (!analysis_id) {
      return NextResponse.json({ error: 'analysis_id requis' }, { status: 400 });
    }

    const supabase = getSupabaseAdmin();

    // Get the analysis
    const { data: analysis } = await supabase
      .from('analyses')
      .select('*')
      .eq('id', analysis_id)
      .single();

    if (!analysis) {
      return NextResponse.json({ error: 'Analyse non trouvée' }, { status: 404 });
    }

    const supplier = analysis.supplier as Supplier;

    // Get all analysis lines
    const { data: lines } = await supabase
      .from('analysis_lines')
      .select('*')
      .eq('analysis_id', analysis_id);

    if (!lines?.length) {
      return NextResponse.json({ error: 'Aucune ligne' }, { status: 400 });
    }

    // Load current product_mappings for this supplier
    const { data: mappings } = await supabase
      .from('product_mappings')
      .select('code_article, matched_product_name, matched_product_id, status, confidence')
      .eq('supplier', supplier);

    const mappingMap = new Map<string, { product_name: string | null; product_id: string | null; status: string | null }>();
    for (const m of mappings ?? []) {
      mappingMap.set(m.code_article, {
        product_name: m.matched_product_name,
        product_id: m.matched_product_id,
        status: m.status,
      });
    }

    // Load reference prices for price lookup
    const { data: refPrices } = await supabase
      .from('reference_prices')
      .select('product_name, price_ht')
      .eq('supplier', supplier)
      .lte('valid_from', analysis.month + '-01')
      .or(`valid_to.is.null,valid_to.gte.${analysis.month}-01`);

    const priceMap = new Map<string, number>();
    for (const p of refPrices ?? []) {
      priceMap.set(p.product_name, p.price_ht);
    }

    // Recalculate each line
    let discrepancyCount = 0;
    let totalOvercharged = 0;
    let matchedLines = 0;
    let unmatchedLines = 0;

    for (const line of lines) {
      const mapping = line.code_article ? mappingMap.get(line.code_article) : null;

      let matchedProduct = line.matched_product;
      let negotiatedPrice = line.negotiated_price;
      let matchMethod = line.match_method;

      if (mapping && mapping.product_name && mapping.status !== 'unknown') {
        // Line is matched via mapping
        matchedProduct = mapping.product_name;
        negotiatedPrice = priceMap.get(mapping.product_name) ?? null;
        if (matchMethod === 'unmatched') matchMethod = 'exact';
        matchedLines++;
      } else if (mapping && mapping.status === 'unknown') {
        // Marked as unknown
        matchedProduct = null;
        negotiatedPrice = null;
        matchMethod = 'unmatched';
        unmatchedLines++;
      } else if (matchMethod !== 'unmatched') {
        matchedLines++;
      } else {
        unmatchedLines++;
      }

      // Update the line
      await supabase
        .from('analysis_lines')
        .update({
          matched_product: matchedProduct,
          negotiated_price: negotiatedPrice,
          match_method: matchMethod,
        })
        .eq('id', line.id);

      // Calculate discrepancy
      const disc = negotiatedPrice !== null
        ? Math.round((Number(line.invoiced_price) - negotiatedPrice) * 100) / 100
        : 0;

      if (disc > 0.01) {
        discrepancyCount++;
        totalOvercharged += disc * (line.quantity || 1);
      }
    }

    totalOvercharged = Math.round(totalOvercharged * 100) / 100;

    // Update analysis totals
    await supabase
      .from('analyses')
      .update({
        discrepancy_count: discrepancyCount,
        total_discrepancies: discrepancyCount,
        total_overcharged: totalOvercharged,
        matched_lines: matchedLines,
        unmatched_lines: unmatchedLines,
      })
      .eq('id', analysis_id);

    return NextResponse.json({
      success: true,
      discrepancy_count: discrepancyCount,
      total_overcharged: totalOvercharged,
      matched_lines: matchedLines,
      unmatched_lines: unmatchedLines,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Erreur inconnue';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
