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

// PUT: Update a product mapping (validate, correct, or mark unknown)
export async function PUT(req: NextRequest) {
  try {
    const body = await req.json();
    const { action, supplier, code_article, new_product_name, analysis_line_id } = body;

    const supabase = getSupabaseAdmin();

    if (action === 'validate') {
      // Mark current mapping as validated
      await supabase
        .from('product_mappings')
        .update({ validated: true })
        .eq('supplier', supplier)
        .eq('code_article', code_article);

      return NextResponse.json({ success: true });
    }

    if (action === 'correct') {
      // Find the new product in reference_prices
      const { data: refPrice } = await supabase
        .from('reference_prices')
        .select('*')
        .eq('supplier', supplier)
        .eq('product_name', new_product_name)
        .is('valid_to', null)
        .limit(1)
        .single();

      if (!refPrice) {
        return NextResponse.json({ error: 'Produit non trouvé dans la base tarifaire' }, { status: 404 });
      }

      // Upsert the mapping
      const { data: existing } = await supabase
        .from('product_mappings')
        .select('id')
        .eq('supplier', supplier)
        .eq('code_article', code_article)
        .limit(1);

      if (existing && existing.length > 0) {
        await supabase
          .from('product_mappings')
          .update({
            matched_product_name: new_product_name,
            matched_product_id: refPrice.id,
            confidence: 'exact',
            validated: true,
          })
          .eq('id', existing[0].id);
      } else {
        await supabase.from('product_mappings').insert({
          supplier,
          code_article,
          matched_product_name: new_product_name,
          matched_product_id: refPrice.id,
          confidence: 'exact',
          validated: true,
        });
      }

      // Update the analysis line if provided
      if (analysis_line_id) {
        await supabase
          .from('analysis_lines')
          .update({
            matched_product: new_product_name,
            negotiated_price: refPrice.price_ht,
            match_method: 'exact',
          })
          .eq('id', analysis_line_id);
      }

      return NextResponse.json({
        success: true,
        product_name: new_product_name,
        price_ht: refPrice.price_ht,
      });
    }

    if (action === 'unknown') {
      // Mark as permanently unmatched
      const { data: existing } = await supabase
        .from('product_mappings')
        .select('id')
        .eq('supplier', supplier)
        .eq('code_article', code_article)
        .limit(1);

      if (existing && existing.length > 0) {
        await supabase
          .from('product_mappings')
          .update({
            matched_product_name: null,
            matched_product_id: null,
            confidence: 'excluded',
            validated: true,
            status: 'unknown',
          })
          .eq('id', existing[0].id);
      } else {
        await supabase.from('product_mappings').insert({
          supplier,
          code_article,
          matched_product_name: null,
          matched_product_id: null,
          confidence: 'excluded',
          validated: true,
          status: 'unknown',
        });
      }

      return NextResponse.json({ success: true });
    }

    if (action === 'add_product') {
      // Create a new reference price AND link the mapping
      const { product_name, category, price_ht } = body;
      if (!product_name || !price_ht) {
        return NextResponse.json({ error: 'product_name et price_ht requis' }, { status: 400 });
      }

      // Insert new reference price
      const { data: newPrice, error: priceError } = await supabase
        .from('reference_prices')
        .insert({
          supplier,
          product_name,
          category: category || 'RIC',
          price_ht: parseFloat(price_ht),
          valid_from: new Date().toISOString().split('T')[0],
          is_manual: true,
        })
        .select()
        .single();

      if (priceError || !newPrice) {
        return NextResponse.json({ error: 'Erreur création produit: ' + priceError?.message }, { status: 500 });
      }

      // Upsert the mapping
      const { data: existing } = await supabase
        .from('product_mappings')
        .select('id')
        .eq('supplier', supplier)
        .eq('code_article', code_article)
        .limit(1);

      if (existing && existing.length > 0) {
        await supabase
          .from('product_mappings')
          .update({
            matched_product_name: product_name,
            matched_product_id: newPrice.id,
            confidence: 'manual',
            validated: true,
            status: 'manual',
          })
          .eq('id', existing[0].id);
      } else {
        await supabase.from('product_mappings').insert({
          supplier,
          code_article,
          description_edi: body.description_edi || null,
          matched_product_name: product_name,
          matched_product_id: newPrice.id,
          confidence: 'manual',
          validated: true,
          status: 'manual',
        });
      }

      // Update analysis line if provided
      if (analysis_line_id) {
        await supabase
          .from('analysis_lines')
          .update({
            matched_product: product_name,
            negotiated_price: parseFloat(price_ht),
            match_method: 'exact',
          })
          .eq('id', analysis_line_id);
      }

      return NextResponse.json({
        success: true,
        product_name,
        price_ht: parseFloat(price_ht),
        product_id: newPrice.id,
      });
    }

    return NextResponse.json({ error: 'Action inconnue' }, { status: 400 });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Erreur inconnue';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

// GET: Search reference prices for autocomplete
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const supplier = searchParams.get('supplier');
    const search = searchParams.get('search');

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

    const supabase = getSupabaseAdmin();
    let query = supabase
      .from('reference_prices')
      .select('id, product_name, price_ht, category')
      .eq('supplier', supplier)
      .is('valid_to', null)
      .order('product_name');

    if (search) {
      query = query.ilike('product_name', `%${search}%`);
    }

    const { data, error } = await query.limit(20);

    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }

    return NextResponse.json(data ?? []);
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Erreur inconnue';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
