// app/api/debug/pdfmonkey-data/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";

export const dynamic = "force-dynamic";

/**
 * API pour tester la récupération des données nécessaires pour PDFMonkey depuis Supabase
 * Usage: GET /api/debug/pdfmonkey-data?contract_id=xxx
 */

// Mapping des champs PDFMonkey vers Supabase (basé sur l'analyse)
const FIELD_MAPPING = {
  // Structure/Organisation data
  structure: {
    table: 'organizations',
    joins: ['cddu_contracts.org_id = organizations.id'],
    fields: {
      structure_name: 'structure_api',
      structure_adresse: 'address',
      structure_cpville: 'postal_code', 
      structure_ville: 'city',
      structure_siret: 'siret',
      structure_licence: 'licence_spectacles',
      forme_juridique: 'legal_form',
      structure_signataire: 'signatory_name',
      structure_signatairequalite: 'signatory_title',
      delegation: 'delegation_authority',
      nom_responsable_traitement: 'data_controller_name',
      qualite_responsable_traitement: 'data_controller_title',
      email_responsable_traitement: 'data_controller_email',
      imageUrl: 'logo_base64'
    }
  },
  
  // Salarié data  
  salarie: {
    table: 'salaries',
    joins: ['cddu_contracts.employee_matricule = salaries.code_salarie'],
    fields: {
      employee_civ: 'civilite',
      employee_firstname: 'prenom',
      employee_lastname: 'nom',
      employee_birthname: 'nom_naissance',
      employee_pseudo: 'pseudonyme',
      employee_dob: 'date_naissance',
      employee_cob: 'lieu_naissance', 
      employee_address: 'adresse',
      employee_ss: 'nir',
      employee_cs: 'conges_spectacles'
    }
  },
  
  // Contract data
  contract: {
    table: 'cddu_contracts',
    fields: {
      employee_profession: 'profession',
      employee_codeprofession: 'code_profession',
      employee_catpro: 'categorie_pro',
      mineur1618: 'mineur_entre_16_et_18',
      representant_civ: 'civilite_representant_legal',
      representant_nom: 'nom_representant_legal', 
      representant_dob: 'dob_representant_legal',
      representant_cob: 'cob_representant_legal',
      representant_adresse: 'adresse_representant_legal',
      spectacle: 'production_name',
      numobjet: 'objet_spectacle',
      type_numobjet: 'type_numero_objet',
      date_debut: 'start_date',
      date_fin: 'end_date',
      dates_travaillees: 'jours_travail',
      autreprecision: 'autre_precision_salaire',
      salaire_brut: 'brut',
      date_signature: 'date_signature_contrat',
      CCN: 'ccn',
      precisions_salaire: 'precisions_salaire',
      panierrepas: 'panier_repas',
      panierrepasccn: 'panier_repas_ccn',
      montantpanierrepas: 'si_non_montant_par_panier',
      'cachets.representations': 'cachets_representations',
      'cachets.repetitions': 'services_repetitions', 
      'cachets.heures': 'nombre_d_heures',
      'cachets.heuresparjour': 'nombre_d_heures_par_jour'
    }
  }
};

function formatDate(dateString: any): string {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0]; // YYYY-MM-DD format
  } catch {
    return String(dateString);
  }
}

async function fetchPDFMonkeyData(supabase: any, contractId: string) {
  console.log("🔍 Récupération des données pour contrat:", contractId);
  
  const results: any = {
    success: false,
    data: {},
    missing_fields: [],
    available_fields: [],
    errors: []
  };
  
  try {
    // 1. Récupérer le contrat principal avec toutes les jointures
    const { data: contractData, error: contractError } = await supabase
      .from('cddu_contracts')
      .select(`
        *,
        organizations!cddu_contracts_org_id_fkey (
          id, name, structure_api, address, postal_code, city, siret,
          licence_spectacles, legal_form, signatory_name, signatory_title,
          delegation_authority, data_controller_name, data_controller_title,
          data_controller_email, logo_base64
        )
      `)
      .eq('id', contractId)
      .single();
    
    if (contractError) {
      results.errors.push(`Erreur contrat: ${contractError.message}`);
      return results;
    }
    
    if (!contractData) {
      results.errors.push("Contrat non trouvé");
      return results;
    }
    
    console.log("📄 Contrat trouvé:", contractData.contract_number);
    
    // 2. Récupérer les données du salarié si matricule disponible
    let salarieData = null;
    if (contractData.employee_matricule) {
      const { data, error } = await supabase
        .from('salaries')
        .select('*')
        .eq('code_salarie', contractData.employee_matricule)
        .single();
        
      if (error) {
        results.errors.push(`Erreur salarié: ${error.message}`);
      } else {
        salarieData = data;
        console.log("👤 Salarié trouvé:", salarieData?.nom, salarieData?.prenom);
      }
    }
    
    // 3. Mapper les données selon le format PDFMonkey
    const dataPayload: any = {};
    
    // Structure data
    const orgData = contractData.organizations;
    if (orgData) {
      Object.entries(FIELD_MAPPING.structure.fields).forEach(([pdfKey, dbColumn]) => {
        const value = orgData[dbColumn];
        if (value !== null && value !== undefined) {
          dataPayload[pdfKey] = value;
          results.available_fields.push(`${pdfKey} (${dbColumn})`);
        } else {
          results.missing_fields.push(`${pdfKey} (organizations.${dbColumn})`);
        }
      });
    }
    
    // Salarié data
    if (salarieData) {
      Object.entries(FIELD_MAPPING.salarie.fields).forEach(([pdfKey, dbColumn]) => {
        const value = salarieData[dbColumn];
        if (value !== null && value !== undefined) {
          dataPayload[pdfKey] = value;
          results.available_fields.push(`${pdfKey} (${dbColumn})`);
        } else {
          results.missing_fields.push(`${pdfKey} (salaries.${dbColumn})`);
        }
      });
    } else {
      // Si pas de salarié trouvé, marquer tous les champs comme manquants
      Object.keys(FIELD_MAPPING.salarie.fields).forEach(pdfKey => {
        results.missing_fields.push(`${pdfKey} (salarié non trouvé)`);
      });
    }
    
    // Contract data
    Object.entries(FIELD_MAPPING.contract.fields).forEach(([pdfKey, dbColumn]) => {
      const value = contractData[dbColumn];
      if (value !== null && value !== undefined) {
        // Formatage spécial pour les dates
        if (pdfKey.includes('date') || pdfKey.includes('dob')) {
          dataPayload[pdfKey] = formatDate(value);
        } else if (pdfKey === 'salaire_brut' && typeof value === 'number') {
          // Formatage du salaire
          dataPayload[pdfKey] = value.toLocaleString('fr-FR', { 
            minimumFractionDigits: 2, 
            maximumFractionDigits: 2 
          });
        } else {
          dataPayload[pdfKey] = value;
        }
        results.available_fields.push(`${pdfKey} (${dbColumn})`);
      } else {
        results.missing_fields.push(`${pdfKey} (cddu_contracts.${dbColumn})`);
      }
    });
    
    // Données additionnelles calculées
    dataPayload.structure_spectacle = contractData.production_name || "";
    
    // Objet cachets
    dataPayload.cachets = {
      representations: contractData.cachets_representations || 0,
      repetitions: contractData.services_repetitions || 0,
      heures: contractData.nombre_d_heures || 0,
      heuresparjour: contractData.nombre_d_heures_par_jour || 0
    };
    
    results.success = true;
    results.data = dataPayload;
    
    console.log("✅ Données récupérées:", {
      available: results.available_fields.length,
      missing: results.missing_fields.length
    });
    
  } catch (error: any) {
    results.errors.push(`Erreur inattendue: ${error.message}`);
    console.error("❌ Erreur lors de la récupération:", error);
  }
  
  return results;
}

export async function GET(req: NextRequest) {
  try {
    const supabase = createSbServer();
    
    // Vérification authentification
    const { data: { user }, error: authError } = await supabase.auth.getUser();
    if (authError || !user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }
    
    const url = new URL(req.url);
    const contractId = url.searchParams.get("contract_id");
    const checkColumns = url.searchParams.get("check_columns") === "true";
    
    if (checkColumns) {
      // Mode vérification des colonnes
      console.log("🔍 Vérification des colonnes disponibles...");
      
      const tables = ['organizations', 'salaries', 'cddu_contracts', 'productions'];
      const columnInfo: any = {};
      
      for (const table of tables) {
        try {
          const { data, error } = await supabase
            .from(table)
            .select('*')
            .limit(1);
          
          if (error) {
            columnInfo[table] = { error: error.message };
          } else if (data && data.length > 0) {
            columnInfo[table] = {
              columns: Object.keys(data[0]),
              sample: data[0]
            };
          } else {
            columnInfo[table] = { columns: [], empty: true };
          }
        } catch (err: any) {
          columnInfo[table] = { error: err.message };
        }
      }
      
      return NextResponse.json({
        mode: "check_columns",
        tables: columnInfo,
        field_mapping: FIELD_MAPPING
      });
    }
    
    if (!contractId) {
      return NextResponse.json({ 
        error: "contract_id requis",
        usage: "GET /api/debug/pdfmonkey-data?contract_id=xxx ou ?check_columns=true"
      }, { status: 400 });
    }
    
    // Mode récupération des données pour un contrat
    const results = await fetchPDFMonkeyData(supabase, contractId);
    
    return NextResponse.json({
      contract_id: contractId,
      timestamp: new Date().toISOString(),
      results,
      comparison_with_airtable: {
        note: "Comparez ces données avec votre payload Airtable actuel",
        missing_critical_fields: results.missing_fields.filter((field: string) => 
          field.includes('structure_name') || 
          field.includes('employee_firstname') || 
          field.includes('employee_lastname') ||
          field.includes('date_debut') ||
          field.includes('date_fin')
        )
      }
    });
    
  } catch (error: any) {
    console.error("❌ Erreur API:", error);
    return NextResponse.json({ 
      error: "Erreur serveur", 
      message: error.message 
    }, { status: 500 });
  }
}