import { NextRequest, NextResponse } from 'next/server';
import { createSbServiceRole } from '@/lib/supabaseServer';
import { ENV } from '@/lib/cleanEnv';

/**
 * POST /api/admin/migrate-employee-slugs
 * 
 * Route admin pour migrer les slugs DocuSeal des salariés
 * depuis l'API DocuSeal vers la table cddu_contracts
 * 
 * Authentification: Requiert un header X-Admin-Key
 */
export async function POST(request: NextRequest) {
  console.log('=== Migration des slugs DocuSeal des salariés ===');

  // Vérification de la clé admin
  const adminKey = request.headers.get('X-Admin-Key');
  if (adminKey !== process.env.ADMIN_API_KEY) {
    return NextResponse.json(
      { error: 'Non autorisé' },
      { status: 401 }
    );
  }

  try {
    const supabase = createSbServiceRole();

    // 1. Récupérer tous les contrats sans employee_docuseal_slug
    const { data: contracts, error: fetchError } = await supabase
      .from('cddu_contracts')
      .select('id, contract_number, docuseal_submission_id, employee_docuseal_slug')
      .not('docuseal_submission_id', 'is', null)
      .is('employee_docuseal_slug', null)
      .limit(100); // Limiter à 100 pour éviter les timeouts

    if (fetchError) {
      console.error('Erreur lors de la récupération des contrats:', fetchError);
      return NextResponse.json(
        { error: 'Erreur lors de la récupération des contrats' },
        { status: 500 }
      );
    }

    if (!contracts || contracts.length === 0) {
      return NextResponse.json({
        success: true,
        message: 'Aucun contrat à migrer',
        migrated: 0,
        total: 0
      });
    }

    console.log(`Nombre de contrats à traiter: ${contracts.length}`);

    let successCount = 0;
    let errorCount = 0;
    const errors: Array<{ contract: string; error: string }> = [];

    // 2. Pour chaque contrat, récupérer le slug depuis DocuSeal
    for (const contract of contracts) {
      try {
        console.log(`Traitement du contrat ${contract.contract_number}...`);

        // Appel à l'API DocuSeal
        const docusealResponse = await fetch(
          `https://api.docuseal.eu/submissions/${contract.docuseal_submission_id}`,
          {
            method: 'GET',
            headers: {
              'X-Auth-Token': ENV.DOCUSEAL_TOKEN,
              'Content-Type': 'application/json',
            },
          }
        );

        if (!docusealResponse.ok) {
          console.error(`Erreur DocuSeal pour ${contract.contract_number}:`, docusealResponse.status);
          errorCount++;
          errors.push({
            contract: contract.contract_number,
            error: `DocuSeal API error: ${docusealResponse.status}`
          });
          continue;
        }

        const docusealData = await docusealResponse.json();
        const submitters = docusealData.submitters || [];
        const employeeSubmitter = submitters.find((s: any) => s.role === 'Salarié');

        if (!employeeSubmitter?.slug) {
          console.warn(`Slug non trouvé pour ${contract.contract_number}`);
          errorCount++;
          errors.push({
            contract: contract.contract_number,
            error: 'Slug non trouvé dans DocuSeal'
          });
          continue;
        }

        // Mise à jour du contrat
        const { error: updateError } = await supabase
          .from('cddu_contracts')
          .update({ employee_docuseal_slug: employeeSubmitter.slug })
          .eq('id', contract.id);

        if (updateError) {
          console.error(`Erreur mise à jour ${contract.contract_number}:`, updateError);
          errorCount++;
          errors.push({
            contract: contract.contract_number,
            error: updateError.message
          });
        } else {
          console.log(`Succès pour ${contract.contract_number}: ${employeeSubmitter.slug}`);
          successCount++;
        }

        // Pause pour éviter de surcharger l'API
        await new Promise(resolve => setTimeout(resolve, 100));

      } catch (error) {
        console.error(`Erreur pour ${contract.contract_number}:`, error);
        errorCount++;
        errors.push({
          contract: contract.contract_number,
          error: error instanceof Error ? error.message : 'Unknown error'
        });
      }
    }

    return NextResponse.json({
      success: true,
      migrated: successCount,
      errors: errorCount,
      total: contracts.length,
      errorDetails: errors.length > 0 ? errors : undefined
    });

  } catch (error) {
    console.error('Erreur lors de la migration:', error);
    return NextResponse.json(
      {
        error: 'Erreur serveur lors de la migration',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}
