const nodemailer = require('nodemailer');
const fs = require('fs');
const path = require('path');

class EmailService {
  constructor(configPath = './config.json') {
    console.log('[EMAIL] ===== INITIALIZING EMAIL SERVICE =====');
    console.log('[EMAIL] Config path:', configPath);
    
    try {
      // Check if config file exists
      if (!fs.existsSync(configPath)) {
        const error = new Error(`Config file not found: ${configPath}`);
        console.error('[EMAIL] ERROR:', error.message);
        throw error;
      }
      
      console.log('[EMAIL] Config file exists, reading...');
      const configContent = fs.readFileSync(configPath, 'utf8');
      console.log('[EMAIL] Config file read successfully');
      
      // Parse JSON
      try {
        this.config = JSON.parse(configContent);
        console.log('[EMAIL] Config JSON parsed successfully');
      } catch (parseError) {
        console.error('[EMAIL] ERROR: Failed to parse config JSON:', parseError.message);
        throw new Error(`Invalid JSON in config file: ${parseError.message}`);
      }
      
      // Check if email section exists
      if (!this.config.email) {
        console.warn('[EMAIL] WARNING: email section missing in config, email service will be disabled');
        this.transporter = null;
        return;
      }
      
      console.log('[EMAIL] Email section found in config');
      
      // Check if SMTP config exists
      if (!this.config.email.smtp) {
        console.warn('[EMAIL] WARNING: smtp config missing, email service will be disabled');
        this.transporter = null;
        return;
      }
      
      // Initialize nodemailer transporter
      try {
        this.transporter = nodemailer.createTransport({
          host: this.config.email.smtp.host,
          port: this.config.email.smtp.port || 587,
          secure: this.config.email.smtp.secure || false, // true for 465, false for other ports
          auth: {
            user: this.config.email.smtp.user,
            pass: this.config.email.smtp.password
          }
        });
        
        console.log('[EMAIL] Nodemailer transporter initialized successfully');
        console.log('[EMAIL] SMTP Host:', this.config.email.smtp.host);
        console.log('[EMAIL] SMTP Port:', this.config.email.smtp.port || 587);
      } catch (transporterError) {
        console.error('[EMAIL] ERROR: Failed to initialize transporter:', transporterError.message);
        this.transporter = null;
        return;
      }
      
      // Load email template
      this.templatePath = this.config.email.template_path || './letter.html';
      if (fs.existsSync(this.templatePath)) {
        this.emailTemplate = fs.readFileSync(this.templatePath, 'utf8');
        console.log('[EMAIL] Email template loaded from:', this.templatePath);
      } else {
        console.warn('[EMAIL] WARNING: Email template not found at:', this.templatePath);
        this.emailTemplate = null;
      }
      
      console.log('[EMAIL] ===== EMAIL SERVICE INITIALIZED SUCCESSFULLY =====');
    } catch (error) {
      console.error('[EMAIL] ===== EMAIL SERVICE INITIALIZATION FAILED =====');
      console.error('[EMAIL] Error type:', error.constructor.name);
      console.error('[EMAIL] Error message:', error.message);
      if (error.stack) {
        console.error('[EMAIL] Error stack:', error.stack);
      }
      console.error('[EMAIL] =================================================');
      this.transporter = null;
      this.emailTemplate = null;
    }
  }

  /**
   * Send confirmation email to customer
   * @param {string} to - Recipient email address
   * @param {Object} sessionData - Stripe session data
   * @returns {Promise<Object>} Email send result
   */
  async sendConfirmationEmail(to, sessionData) {
    if (!this.transporter) {
      throw new Error('Email service not initialized - check SMTP configuration');
    }

    if (!to || !to.includes('@')) {
      throw new Error('Invalid recipient email address');
    }

    try {
      // Build email content
      const emailContent = this.buildEmailContent(sessionData);
      
      const mailOptions = {
        from: this.config.email.from || 'noreply@example.com',
        to: to,
        subject: this.config.email.subject || 'Booking Confirmation',
        html: emailContent
      };

      console.log('[EMAIL] Sending confirmation email to:', to);
      console.log('[EMAIL] Session ID:', sessionData?.id || 'N/A');
      
      const info = await this.transporter.sendMail(mailOptions);
      
      console.log('[EMAIL] ===== EMAIL SENT SUCCESSFULLY =====');
      console.log('[EMAIL] Message ID:', info.messageId);
      console.log('[EMAIL] Response:', info.response);
      console.log('[EMAIL] ====================================');
      
      return info;
    } catch (error) {
      console.error('[EMAIL] ===== EMAIL SEND FAILED =====');
      console.error('[EMAIL] Error message:', error.message);
      console.error('[EMAIL] Error code:', error.code || 'N/A');
      console.error('[EMAIL] =============================');
      throw error;
    }
  }

  /**
   * Build email content from template and session data
   * @param {Object} sessionData - Stripe session data
   * @returns {string} HTML email content
   */
  buildEmailContent(sessionData) {
    // If template exists, use it and replace placeholders
    if (this.emailTemplate) {
      let content = this.emailTemplate;
      
      // Replace common placeholders with session data
      const replacements = {
        '{{SESSION_ID}}': sessionData?.id || 'N/A',
        '{{AMOUNT}}': sessionData?.amount_total ? `$${(sessionData.amount_total / 100).toFixed(2)}` : 'N/A',
        '{{CURRENCY}}': sessionData?.currency?.toUpperCase() || 'USD',
        '{{CUSTOMER_EMAIL}}': sessionData?.customer_email || 'N/A',
        '{{PAYMENT_STATUS}}': sessionData?.payment_status || 'N/A',
        '{{CRUISE_TITLE}}': sessionData?.metadata?.cruise_title || 'Cruise Booking',
        '{{SHIP_NAME}}': sessionData?.metadata?.ship_name || 'N/A',
        '{{SAIL_DATE}}': sessionData?.metadata?.sail_date || 'N/A',
        '{{GUEST_NAME}}': sessionData?.metadata?.guest_name || 'Guest',
        '{{PACKAGE_ID}}': sessionData?.metadata?.package_id || 'N/A',
        '{{DATE}}': new Date().toLocaleDateString('en-US', { 
          year: 'numeric', 
          month: 'long', 
          day: 'numeric' 
        })
      };
      
      // Replace all placeholders
      Object.keys(replacements).forEach(placeholder => {
        content = content.replace(new RegExp(placeholder, 'g'), replacements[placeholder]);
      });
      
      return content;
    }
    
    // Fallback: simple HTML template
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <style>
          body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
          .container { max-width: 600px; margin: 0 auto; padding: 20px; }
          .header { background-color: #f4f4f4; padding: 20px; text-align: center; }
          .content { padding: 20px; }
          .footer { background-color: #f4f4f4; padding: 20px; text-align: center; font-size: 12px; color: #666; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Thank You!</h1>
          </div>
          <div class="content">
            <p>Your booking has been confirmed.</p>
            <p><strong>Booking Details:</strong></p>
            <ul>
              <li>Session ID: ${sessionData?.id || 'N/A'}</li>
              <li>Amount: ${sessionData?.amount_total ? `$${(sessionData.amount_total / 100).toFixed(2)}` : 'N/A'} ${sessionData?.currency?.toUpperCase() || 'USD'}</li>
              <li>Payment Status: ${sessionData?.payment_status || 'N/A'}</li>
            </ul>
            ${sessionData?.metadata?.cruise_title ? `<p><strong>Cruise:</strong> ${sessionData.metadata.cruise_title}</p>` : ''}
            ${sessionData?.metadata?.ship_name ? `<p><strong>Ship:</strong> ${sessionData.metadata.ship_name}</p>` : ''}
            ${sessionData?.metadata?.sail_date ? `<p><strong>Sail Date:</strong> ${sessionData.metadata.sail_date}</p>` : ''}
            <p>You will receive your electronic tickets via email 14 days before the start of the cruise.</p>
          </div>
          <div class="footer">
            <p>Thank you for choosing us!</p>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Test email service
   * @param {string} testEmail - Email address to send test to
   * @returns {Promise<Object>} Test result
   */
  async sendTestEmail(testEmail) {
    if (!this.transporter) {
      throw new Error('Email service not initialized');
    }

    const testSessionData = {
      id: 'test_session_123',
      amount_total: 10000, // $100.00
      currency: 'usd',
      payment_status: 'paid',
      customer_email: testEmail,
      metadata: {
        cruise_title: 'Test Cruise',
        ship_name: 'Test Ship',
        sail_date: '2025-12-31',
        guest_name: 'Test Guest',
        package_id: 'TEST123'
      }
    };

    return await this.sendConfirmationEmail(testEmail, testSessionData);
  }
}

module.exports = EmailService;

