/**
 * Script de test pour vérifier l'envoi d'email aux transporteurs
 *
 * Usage: node test-carrier-email-fix.js
 */

const nodemailer = require('nodemailer');

async function testEmailConfig() {
  console.log('🔍 Test de configuration email Mailtrap...\n');

  const config = {
    host: process.env.SMTP_HOST || 'sandbox.smtp.mailtrap.io',
    port: parseInt(process.env.SMTP_PORT || '2525'),
    user: process.env.SMTP_USER || '2597bd31d265eb',
    pass: process.env.SMTP_PASS || 'cd126234193c89',
  };

  console.log('📧 Configuration SMTP:');
  console.log(`  Host: ${config.host}`);
  console.log(`  Port: ${config.port}`);
  console.log(`  User: ${config.user}`);
  console.log(`  Pass: ${config.pass.substring(0, 4)}***\n`);

  // Test 1: Configuration standard (peut échouer avec timeout DNS)
  console.log('Test 1: Configuration standard...');
  try {
    const transporter1 = nodemailer.createTransport({
      host: config.host,
      port: config.port,
      secure: false,
      auth: {
        user: config.user,
        pass: config.pass,
      },
      connectionTimeout: 10000,
      greetingTimeout: 10000,
      socketTimeout: 30000,
    });

    await transporter1.sendMail({
      from: 'noreply@xpeditis.com',
      to: 'test@xpeditis.com',
      subject: 'Test Email - Configuration Standard',
      html: '<h1>Test réussi!</h1><p>Configuration standard fonctionne.</p>',
    });

    console.log('✅ Test 1 RÉUSSI - Configuration standard OK\n');
  } catch (error) {
    console.error('❌ Test 1 ÉCHOUÉ:', error.message);
    console.error('   Code:', error.code);
    console.error('   Timeout?', error.message.includes('ETIMEOUT'));
    console.log('');
  }

  // Test 2: Configuration avec IP directe (devrait toujours fonctionner)
  console.log('Test 2: Configuration avec IP directe...');
  try {
    const useDirectIP = config.host.includes('mailtrap.io');
    const actualHost = useDirectIP ? '3.209.246.195' : config.host;
    const serverName = useDirectIP ? 'smtp.mailtrap.io' : config.host;

    console.log(`  Utilisation IP directe: ${useDirectIP}`);
    console.log(`  Host réel: ${actualHost}`);
    console.log(`  Server name (TLS): ${serverName}`);

    const transporter2 = nodemailer.createTransport({
      host: actualHost,
      port: config.port,
      secure: false,
      auth: {
        user: config.user,
        pass: config.pass,
      },
      tls: {
        rejectUnauthorized: false,
        servername: serverName,
      },
      connectionTimeout: 10000,
      greetingTimeout: 10000,
      socketTimeout: 30000,
      dnsTimeout: 10000,
    });

    const result = await transporter2.sendMail({
      from: 'noreply@xpeditis.com',
      to: 'test@xpeditis.com',
      subject: 'Test Email - Configuration IP Directe',
      html: '<h1>Test réussi!</h1><p>Configuration avec IP directe fonctionne.</p>',
    });

    console.log('✅ Test 2 RÉUSSI - Configuration IP directe OK');
    console.log(`   Message ID: ${result.messageId}`);
    console.log(`   Response: ${result.response}\n`);
  } catch (error) {
    console.error('❌ Test 2 ÉCHOUÉ:', error.message);
    console.error('   Code:', error.code);
    console.log('');
  }

  // Test 3: Template HTML de booking transporteur
  console.log('Test 3: Envoi avec template HTML complet...');
  try {
    const useDirectIP = config.host.includes('mailtrap.io');
    const actualHost = useDirectIP ? '3.209.246.195' : config.host;
    const serverName = useDirectIP ? 'smtp.mailtrap.io' : config.host;

    const transporter3 = nodemailer.createTransport({
      host: actualHost,
      port: config.port,
      secure: false,
      auth: {
        user: config.user,
        pass: config.pass,
      },
      tls: {
        rejectUnauthorized: false,
        servername: serverName,
      },
      connectionTimeout: 10000,
      greetingTimeout: 10000,
      socketTimeout: 30000,
      dnsTimeout: 10000,
    });

    const bookingData = {
      bookingId: 'TEST-' + Date.now(),
      origin: 'FRPAR',
      destination: 'USNYC',
      volumeCBM: 10.5,
      weightKG: 850,
      palletCount: 4,
      priceUSD: 1500,
      priceEUR: 1350,
      primaryCurrency: 'USD',
      transitDays: 15,
      containerType: '20FT',
      documents: [
        { type: 'Bill of Lading', fileName: 'bol.pdf' },
        { type: 'Packing List', fileName: 'packing_list.pdf' },
      ],
      acceptUrl: 'http://localhost:3000/carrier/booking/accept',
      rejectUrl: 'http://localhost:3000/carrier/booking/reject',
    };

    const htmlTemplate = `
      <!DOCTYPE html>
      <html>
      <head><meta charset="UTF-8"></head>
      <body style="font-family: Arial, sans-serif; background-color: #f4f6f8; padding: 20px;">
        <div style="max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden;">
          <div style="background: linear-gradient(135deg, #045a8d, #00bcd4); color: white; padding: 30px; text-align: center;">
            <h1 style="margin: 0;">🚢 Nouvelle demande de réservation</h1>
            <p style="margin: 5px 0 0;">Xpeditis</p>
          </div>
          <div style="padding: 30px;">
            <p style="font-size: 16px;">Bonjour,</p>
            <p>Vous avez reçu une nouvelle demande de réservation via Xpeditis.</p>
            <h2 style="color: #045a8d; border-bottom: 2px solid #00bcd4; padding-bottom: 8px;">📋 Détails du transport</h2>
            <table style="width: 100%; border-collapse: collapse;">
              <tr style="border-bottom: 1px solid #e0e0e0;">
                <td style="padding: 12px; font-weight: bold; color: #045a8d;">Route</td>
                <td style="padding: 12px;">${bookingData.origin} → ${bookingData.destination}</td>
              </tr>
              <tr style="border-bottom: 1px solid #e0e0e0;">
                <td style="padding: 12px; font-weight: bold; color: #045a8d;">Volume</td>
                <td style="padding: 12px;">${bookingData.volumeCBM} CBM</td>
              </tr>
              <tr style="border-bottom: 1px solid #e0e0e0;">
                <td style="padding: 12px; font-weight: bold; color: #045a8d;">Prix</td>
                <td style="padding: 12px; font-size: 24px; font-weight: bold; color: #00aa00;">
                  ${bookingData.priceUSD} USD
                </td>
              </tr>
            </table>
            <div style="text-align: center; margin: 30px 0;">
              <p style="font-weight: bold;">Veuillez confirmer votre décision :</p>
              <a href="${bookingData.acceptUrl}" style="display: inline-block; padding: 15px 30px; background: #00aa00; color: white; text-decoration: none; border-radius: 6px; margin: 0 5px;">✓ Accepter</a>
              <a href="${bookingData.rejectUrl}" style="display: inline-block; padding: 15px 30px; background: #cc0000; color: white; text-decoration: none; border-radius: 6px; margin: 0 5px;">✗ Refuser</a>
            </div>
            <div style="background: #fff8e1; border-left: 4px solid #f57c00; padding: 15px; margin: 20px 0;">
              <p style="margin: 0; font-size: 14px; color: #666;">
                <strong style="color: #f57c00;">⚠️ Important</strong><br>
                Cette demande expire automatiquement dans 7 jours si aucune action n'est prise.
              </p>
            </div>
          </div>
          <div style="background: #f4f6f8; padding: 20px; text-align: center; font-size: 12px; color: #666;">
            <p style="margin: 5px 0; font-weight: bold; color: #045a8d;">Référence : ${bookingData.bookingId}</p>
            <p style="margin: 5px 0;">© 2025 Xpeditis. Tous droits réservés.</p>
          </div>
        </div>
      </body>
      </html>
    `;

    const result = await transporter3.sendMail({
      from: 'noreply@xpeditis.com',
      to: 'carrier@test.com',
      subject: `Nouvelle demande de réservation - ${bookingData.origin} → ${bookingData.destination}`,
      html: htmlTemplate,
    });

    console.log('✅ Test 3 RÉUSSI - Email complet avec template envoyé');
    console.log(`   Message ID: ${result.messageId}`);
    console.log(`   Response: ${result.response}\n`);
  } catch (error) {
    console.error('❌ Test 3 ÉCHOUÉ:', error.message);
    console.error('   Code:', error.code);
    console.log('');
  }

  console.log('📊 Résumé des tests:');
  console.log('   ✓ Vérifiez Mailtrap inbox: https://mailtrap.io/inboxes');
  console.log('   ✓ Recherchez les emails de test ci-dessus');
  console.log(
    '   ✓ Si Test 2 et 3 réussissent, le backend doit être corrigé avec la configuration IP directe\n'
  );
}

// Run test
testEmailConfig()
  .then(() => {
    console.log('✅ Tests terminés avec succès');
    process.exit(0);
  })
  .catch(error => {
    console.error('❌ Erreur lors des tests:', error);
    process.exit(1);
  });
