import React from 'react';
import ReactPDF from '@react-pdf/renderer';
import { ContratCDDU } from './templates/ContratCDDU';
import { ContratCDDUData } from './types';
import { uploadPdfToS3, generateContractS3Key } from './uploadPdf';

export interface GenerateContractResult {
  /** Clé S3 du fichier uploadé */
  s3Key: string;
  /** URL complète S3 (non signée) */
  s3Url: string;
  /** Taille du PDF en bytes */
  size: number;
}

/**
 * Génère un contrat CDDU en PDF et l'upload sur S3
 * 
 * @param data - Données du contrat
 * @param organizationId - ID de l'organisation
 * @param contractId - ID du contrat
 * @returns Informations sur le fichier uploadé
 * 
 * @example
 * ```typescript
 * const result = await generateAndUploadContract(
 *   contractData,
 *   'org-123',
 *   'contract-456'
 * );
 * 
 * console.log('PDF uploadé:', result.s3Key);
 * // Enregistrer result.s3Key dans Supabase
 * ```
 */
export async function generateAndUploadContract(
  data: ContratCDDUData,
  organizationId: string,
  contractId: string
): Promise<GenerateContractResult> {
  console.log('🚀 [Contract Generation] Début de la génération du contrat:', {
    organizationId,
    contractId,
  });

  try {
    // 1. Générer le PDF
    console.log('📄 [Contract Generation] Génération du PDF...');
    const doc = <ContratCDDU data={data} />;
    const pdfBlob = await ReactPDF.pdf(doc).toBlob();
    
    // Convertir le Blob en Buffer
    const arrayBuffer = await pdfBlob.arrayBuffer();
    const pdfBuffer = Buffer.from(arrayBuffer);
    
    console.log(`✅ [Contract Generation] PDF généré (${pdfBuffer.byteLength} bytes)`);

    // 2. Générer la clé S3
    const year = new Date(data.date_debut).getFullYear();
    const s3Key = generateContractS3Key(organizationId, contractId, year);

    // 3. Upload sur S3
    console.log('📤 [Contract Generation] Upload sur S3...');
    await uploadPdfToS3({
      pdfBuffer,
      key: s3Key,
      metadata: {
        contractId,
        organizationId,
        employeeName: `${data.employee_firstname} ${data.employee_lastname}`,
        contractType: 'CDDU',
        generatedAt: new Date().toISOString(),
      },
    });

    // 4. Construire l'URL S3
    const region = process.env.AWS_REGION || 'eu-west-3';
    const bucket = process.env.AWS_S3_BUCKET || 'odentas-docs';
    const s3Url = `https://${bucket}.s3.${region}.amazonaws.com/${s3Key}`;

    console.log('✅ [Contract Generation] Contrat généré et uploadé avec succès:', {
      s3Key,
      s3Url,
      size: pdfBuffer.byteLength,
    });

    return {
      s3Key,
      s3Url,
      size: pdfBuffer.byteLength,
    };
  } catch (error) {
    console.error('❌ [Contract Generation] Erreur lors de la génération du contrat:', error);
    throw new Error(
      `Échec de la génération du contrat: ${error instanceof Error ? error.message : String(error)}`
    );
  }
}

/**
 * Génère uniquement le PDF sans l'uploader (utile pour les tests)
 * 
 * @param data - Données du contrat
 * @returns Buffer du PDF
 */
export async function generateContractPdf(data: ContratCDDUData): Promise<Buffer> {
  console.log('📄 [Contract Generation] Génération du PDF uniquement...');
  
  const doc = <ContratCDDU data={data} />;
  const pdfBlob = await ReactPDF.pdf(doc).toBlob();
  
  const arrayBuffer = await pdfBlob.arrayBuffer();
  const pdfBuffer = Buffer.from(arrayBuffer);
  
  console.log(`✅ [Contract Generation] PDF généré (${pdfBuffer.byteLength} bytes)`);
  
  return pdfBuffer;
}
