// scripts/test-email.js - Test Email Configuration
require('dotenv').config();
const nodemailer = require('nodemailer');

console.log('\n🧪 Testing Namecheap Email Configuration...\n');

// Display current configuration
console.log('📋 Current SMTP Settings:');
console.log('─'.repeat(50));
console.log(`Host:     ${process.env.SMTP_HOST}`);
console.log(`Port:     ${process.env.SMTP_PORT}`);
console.log(`Secure:   ${process.env.SMTP_SECURE}`);
console.log(`User:     ${process.env.SMTP_USER}`);
console.log(`From:     ${process.env.SMTP_FROM}`);
console.log('─'.repeat(50));
console.log('');

// Create transporter
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: parseInt(process.env.SMTP_PORT || '587'),
  secure: process.env.SMTP_SECURE === 'true',
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASSWORD,
  },
  tls: {
    rejectUnauthorized: process.env.NODE_ENV === 'production'
  }
});

// Test connection
async function testEmailConfiguration() {
  try {
    console.log('⏳ Step 1: Verifying SMTP connection...');
    await transporter.verify();
    console.log('✅ SMTP connection verified successfully!\n');

    // Ask user if they want to send a test email
    console.log('⏳ Step 2: Sending test email...');

    const testMailOptions = {
      from: process.env.SMTP_FROM || 'WakaTraffic <noreply@wakatraffic.ng>',
      to: process.env.SMTP_USER, // Send to yourself for testing
      subject: '✅ WakaTraffic Email Test - Success!',
      html: getTestEmailTemplate(),
      text: 'This is a test email from WakaTraffic. If you received this, your email configuration is working correctly!'
    };

    const info = await transporter.sendMail(testMailOptions);
    console.log('✅ Test email sent successfully!');
    console.log('📧 Message ID:', info.messageId);
    console.log('📬 Email sent to:', process.env.SMTP_USER);
    console.log('');
    console.log('─'.repeat(50));
    console.log('🎉 All tests passed! Email configuration is working correctly.');
    console.log('─'.repeat(50));
    console.log('');
    console.log('Next steps:');
    console.log('1. Check your inbox:', process.env.SMTP_USER);
    console.log('2. Verify the test email arrived (check spam folder too)');
    console.log('3. If successful, your email service is ready for production!');
    console.log('');

    process.exit(0);

  } catch (error) {
    console.error('');
    console.error('❌ Email configuration test failed!');
    console.error('─'.repeat(50));
    console.error('Error:', error.message);
    console.error('');

    // Provide helpful troubleshooting tips
    console.error('💡 Troubleshooting Tips:');
    console.error('');

    if (error.message.includes('authentication') || error.message.includes('auth')) {
      console.error('🔐 Authentication Error:');
      console.error('   • Verify SMTP_USER is your FULL email (e.g., noreply@wakatraffic.ng)');
      console.error('   • Check SMTP_PASSWORD is correct (email password, not Namecheap login)');
      console.error('   • Try logging into webmail: https://privateemail.com');
    }

    if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {
      console.error('⏱️  Connection Timeout:');
      console.error('   • Port 465 may be blocked by your firewall/ISP');
      console.error('   • Try switching to port 587 with SMTP_SECURE=false');
      console.error('   • Check if your server allows outbound SMTP connections');
    }

    if (error.message.includes('ECONNREFUSED')) {
      console.error('🚫 Connection Refused:');
      console.error('   • Check SMTP_HOST is correct: mail.privateemail.com');
      console.error('   • Verify your internet connection is working');
      console.error('   • Make sure SMTP_PORT is 465 or 587');
    }

    if (error.message.includes('certificate') || error.message.includes('TLS')) {
      console.error('🔒 SSL/TLS Error:');
      console.error('   • Try setting NODE_ENV=development in .env');
      console.error('   • This will disable strict certificate validation for testing');
    }

    console.error('');
    console.error('📖 For detailed setup instructions, see:');
    console.error('   ./NAMECHEAP_EMAIL_SETUP.md');
    console.error('');

    process.exit(1);
  }
}

// Test email template
function getTestEmailTemplate() {
  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Test</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4; padding: 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
          <!-- Header -->
          <tr>
            <td style="background: linear-gradient(135deg, #27AE60 0%, #1E8449 100%); padding: 40px 20px; text-align: center;">
              <h1 style="color: #ffffff; margin: 0; font-size: 28px;">✅ Email Test Successful!</h1>
              <p style="color: #ffffff; margin: 10px 0 0 0; opacity: 0.9;">WakaTraffic Email Service</p>
            </td>
          </tr>

          <!-- Content -->
          <tr>
            <td style="padding: 40px 30px;">
              <h2 style="color: #333333; margin: 0 0 20px 0; font-size: 24px;">Congratulations! 🎉</h2>
              <p style="color: #666666; line-height: 1.6; margin: 0 0 20px 0;">
                Your Namecheap email SMTP configuration is working correctly. This test email confirms that:
              </p>

              <ul style="color: #666666; line-height: 1.8; margin: 0 0 20px 0;">
                <li>✅ SMTP server connection is established</li>
                <li>✅ Authentication credentials are valid</li>
                <li>✅ Email delivery is functioning</li>
                <li>✅ Email templates render correctly</li>
              </ul>

              <!-- Settings Box -->
              <table width="100%" cellpadding="15" style="margin: 20px 0; border: 2px solid #27AE60; border-radius: 8px; background-color: #f8f9fa;">
                <tr>
                  <td>
                    <p style="color: #27AE60; margin: 0 0 10px 0; font-weight: bold; font-size: 16px;">📋 Configuration Details</p>
                    <p style="color: #666666; margin: 5px 0; font-size: 14px;"><strong>SMTP Host:</strong> ${process.env.SMTP_HOST}</p>
                    <p style="color: #666666; margin: 5px 0; font-size: 14px;"><strong>SMTP Port:</strong> ${process.env.SMTP_PORT}</p>
                    <p style="color: #666666; margin: 5px 0; font-size: 14px;"><strong>From Email:</strong> ${process.env.SMTP_FROM}</p>
                    <p style="color: #666666; margin: 5px 0; font-size: 14px;"><strong>Test Date:</strong> ${new Date().toLocaleString()}</p>
                  </td>
                </tr>
              </table>

              <p style="color: #666666; line-height: 1.6; margin: 20px 0 0 0;">
                Your WakaTraffic platform can now send:
              </p>
              <ul style="color: #666666; line-height: 1.8;">
                <li>📧 OTP verification emails</li>
                <li>🔒 Password reset emails</li>
                <li>👋 Welcome emails</li>
                <li>📦 Order confirmation emails</li>
              </ul>

              <p style="color: #27AE60; font-weight: bold; margin: 20px 0 0 0; font-size: 16px;">
                ✅ Your email service is production-ready!
              </p>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background-color: #f8f9fa; padding: 30px; text-align: center; border-top: 1px solid #e9ecef;">
              <p style="color: #666666; margin: 0 0 10px 0; font-size: 14px;">
                WakaTraffic - Social Media Marketing Platform
              </p>
              <p style="color: #999999; margin: 0; font-size: 12px;">
                © ${new Date().getFullYear()} WakaTraffic. All rights reserved.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

// Run the test
testEmailConfiguration();
