#!/usr/bin/env node

/**
 * Script de test Odentas Sign
 * 
 * Upload un PDF local vers S3 et crée une demande de signature
 */

const fs = require('fs');
const path = require('path');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');

// Configuration
const PDF_PATH = path.join(__dirname, 'test-contrat.pdf');
const BUCKET = process.env.ODENTAS_SIGN_BUCKET || 'odentas-sign';
const REGION = process.env.AWS_REGION || 'eu-west-3';
const API_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

// Emails pour le test
const EMPLOYEUR_EMAIL = 'paie@odentas.fr';
const SALARIE_EMAIL = 'renaud.breviere@gmail.com';

async function main() {
  console.log('🚀 Odentas Sign - Script de test local\n');
  
  // 1. Vérifier que le PDF existe
  if (!fs.existsSync(PDF_PATH)) {
    console.error(`❌ PDF introuvable: ${PDF_PATH}`);
    process.exit(1);
  }
  
  const pdfBuffer = fs.readFileSync(PDF_PATH);
  console.log(`✅ PDF chargé: ${PDF_PATH} (${(pdfBuffer.length / 1024).toFixed(1)} KB)\n`);
  
  // 2. Upload vers S3
  console.log('📤 Upload du PDF vers S3...');
  const testRef = `TEST-${Date.now()}`;
  const s3Key = `source/test/${testRef}.pdf`;
  
  const s3Client = new S3Client({ region: REGION });
  
  try {
    await s3Client.send(new PutObjectCommand({
      Bucket: BUCKET,
      Key: s3Key,
      Body: pdfBuffer,
      ContentType: 'application/pdf',
      Metadata: {
        test: 'true',
        uploaded_by: 'test-script',
        original_name: 'test-contrat.pdf',
      },
    }));
    
    console.log(`✅ PDF uploadé: s3://${BUCKET}/${s3Key}\n`);
  } catch (error) {
    console.error('❌ Erreur upload S3:', error.message);
    console.error('   Vérifiez vos credentials AWS dans .env.local');
    process.exit(1);
  }
  
  // 3. Créer la demande de signature via l'API
  console.log('📝 Création de la demande de signature...');
  
  const requestBody = {
    contractId: `test-local-${Date.now()}`,
    contractRef: testRef,
    pdfS3Key: s3Key,
    title: 'Contrat CDDU - Test Local',
    signers: [
      {
        role: 'Employeur',
        name: 'Odentas Paie',
        email: EMPLOYEUR_EMAIL,
      },
      {
        role: 'Salarié',
        name: 'Renaud Breviere',
        email: SALARIE_EMAIL,
      },
    ],
    positions: [
      {
        role: 'Employeur',
        page: 3,
        x: 20,
        y: 260,
        w: 150,
        h: 60,
        kind: 'signature',
        label: 'Signature Employeur',
      },
      {
        role: 'Salarié',
        page: 3,
        x: 180,
        y: 260,
        w: 150,
        h: 60,
        kind: 'signature',
        label: 'Signature Employé',
      },
    ],
  };
  
  try {
    const response = await fetch(`${API_URL}/api/odentas-sign/requests/create`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(requestBody),
    });
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || `HTTP ${response.status}`);
    }
    
    const result = await response.json();
    
    console.log('✅ Demande créée avec succès!\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('📋 INFORMATIONS DE LA DEMANDE');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log(`ID:     ${result.request.id}`);
    console.log(`Ref:    ${result.request.ref}`);
    console.log(`Titre:  ${result.request.title}`);
    console.log(`Statut: ${result.request.status}\n`);
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('👥 SIGNATAIRES');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    result.signers.forEach((signer, index) => {
      console.log(`${index + 1}. ${signer.role} - ${signer.name}`);
      console.log(`   Email: ${signer.email}`);
      console.log(`   ID:    ${signer.signerId}`);
      console.log(`   URL:   ${signer.signatureUrl}\n`);
    });
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('🧪 INSTRUCTIONS DE TEST');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    console.log('Étape 1: Demander un code OTP');
    console.log('─────────────────────────────────\n');
    result.signers.forEach((signer, index) => {
      console.log(`${signer.role}:`);
      console.log(`curl -X POST ${API_URL}/api/odentas-sign/signers/${signer.signerId}/send-otp\n`);
    });
    
    console.log('\n📧 Les codes OTP seront envoyés aux emails:');
    console.log(`   - ${EMPLOYEUR_EMAIL}`);
    console.log(`   - ${SALARIE_EMAIL}\n`);
    
    console.log('⚠️  En mode TEST, les codes apparaissent aussi dans les logs serveur\n');
    
    console.log('\nÉtape 2: Vérifier le code OTP');
    console.log('─────────────────────────────────\n');
    console.log(`curl -X POST ${API_URL}/api/odentas-sign/signers/[SIGNER_ID]/verify-otp \\`);
    console.log(`  -H "Content-Type: application/json" \\`);
    console.log(`  -d '{"otp": "123456"}'\n`);
    
    console.log('\nÉtape 3: Enregistrer la signature');
    console.log('─────────────────────────────────\n');
    console.log(`curl -X POST ${API_URL}/api/odentas-sign/signers/[SIGNER_ID]/sign \\`);
    console.log(`  -H "Content-Type: application/json" \\`);
    console.log(`  -H "Authorization: Bearer [SESSION_TOKEN]" \\`);
    console.log(`  -d '{"signatureImageBase64": "data:image/png;base64,iVBORw0...", "consentText": "Je consens"}'\n`);
    
    console.log('\n💡 Pour plus de détails, voir: ODENTAS_SIGN_TEST_GUIDE.md\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Sauvegarder les infos pour référence
    const testInfoPath = path.join(__dirname, 'test-odentas-sign-info.json');
    fs.writeFileSync(testInfoPath, JSON.stringify(result, null, 2));
    console.log(`💾 Informations sauvegardées dans: ${testInfoPath}\n`);
    
  } catch (error) {
    console.error('❌ Erreur création demande:', error.message);
    process.exit(1);
  }
}

main().catch(console.error);
