const nodemailer = require('nodemailer');

// Validate environment variables
const SMTP_HOST = process.env.SMTP_HOST || 'mail.wavecost.com';
const SMTP_PORT = parseInt(process.env.SMTP_PORT) || 587;
const SMTP_SECURE = process.env.SMTP_SECURE === 'true';
const SMTP_USER = process.env.SMTP_USER || 'no-reply@wavecost.com';
const SMTP_PASS = process.env.SMTP_PASS || 'ANDREW@andrew2002';
const SMTP_FROM = process.env.SMTP_FROM || 'no-reply@wavecost.com';
const SMTP_REJECT_UNAUTHORIZED = process.env.SMTP_REJECT_UNAUTHORIZED !== 'false';

const emailTransporter = nodemailer.createTransport({
  host: SMTP_HOST,
  port: SMTP_PORT,
  secure: SMTP_SECURE,
  auth: {
    user: SMTP_USER,
    pass: SMTP_PASS
  },
  tls: {
    // Disable certificate validation
    rejectUnauthorized: false
  }
});

// Verify transporter connection on startup
emailTransporter.verify((error) => {
  if (error) {
    console.error('Error verifying email transporter:', error);
  } else {
    console.log('Email transporter is ready to send messages');
  }
});

class Email {
  static async sendOTPEmail(email, otp) {
    if (!email || !otp) {
      throw new Error('Email and OTP are required');
    }

    try {
      const mailOptions = {
        from: `"WaveCost" <${SMTP_FROM}>`,
        to: email,
        subject: 'Your OTP Code',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #0066cc;">WaveCost OTP Verification</h2>
            <p>Your One-Time Password (OTP) is:</p>
            <div style="background: #f4f4f4; padding: 10px; margin: 15px 0; font-size: 24px; font-weight: bold; letter-spacing: 2px; text-align: center;">
              ${otp}
            </div>
            <p>This OTP is valid for 10 minutes. Please do not share it with anyone.</p>
            <p>If you didn't request this OTP, please ignore this email.</p>
            <p style="margin-top: 20px; font-size: 12px; color: #666;">
              © ${new Date().getFullYear()} WaveCost. All rights reserved.
            </p>
          </div>
        `,
        text: `Your WaveCost OTP is: ${otp}\n\nThis OTP is valid for 10 minutes.\n\nIf you didn't request this OTP, please ignore this email.`
      };

      const info = await emailTransporter.sendMail(mailOptions);
      console.log(`OTP email sent to ${email}`, info.messageId);
      return true;
    } catch (error) {
      console.error('Error sending OTP email:', error);
      throw new Error('Failed to send OTP email');
    }
  }

  // In your email model (add these methods to the Email class)
static async sendPaymentSuccessEmail(email, amount) {
    if (!email || !amount) {
        throw new Error('Email and amount are required');
    }

    try {
        const mailOptions = {
            from: `"WaveCost" <${SMTP_FROM}>`,
            to: email,
            subject: 'Payment Successful',
            html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <h2 style="color: #0066cc;">Payment Received</h2>
                    <p>Your payment of <strong>MWK ${amount}</strong> was successfully processed.</p>
                    <p>Thank you for your support!</p>
                    <p style="margin-top: 20px; font-size: 12px; color: #666;">
                        © ${new Date().getFullYear()} WaveCost. All rights reserved.
                    </p>
                </div>
            `,
            text: `Your payment of MWK ${amount} was successfully processed.\n\nThank you for your support!`
        };

        const info = await emailTransporter.sendMail(mailOptions);
        console.log(`Payment success email sent to ${email}`, info.messageId);
        return true;
    } catch (error) {
        console.error('Error sending payment success email:', error);
        throw new Error('Failed to send payment success email');
    }
}

static async sendPaymentFailedEmail(email, amount) {
    if (!email || !amount) {
        throw new Error('Email and amount are required');
    }

    try {
        const mailOptions = {
            from: `"WaveCost" <${SMTP_FROM}>`,
            to: email,
            subject: 'Payment Failed',
            html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <h2 style="color: #cc0000;">Payment Failed</h2>
                    <p>We were unable to process your payment of <strong>MWK ${amount}</strong>.</p>
                    <p>Please try again or contact support if the problem persists.</p>
                    <p style="margin-top: 20px; font-size: 12px; color: #666;">
                        © ${new Date().getFullYear()} WaveCost. All rights reserved.
                    </p>
                </div>
            `,
            text: `We were unable to process your payment of MWK ${amount}.\n\nPlease try again or contact support if the problem persists.`
        };

        const info = await emailTransporter.sendMail(mailOptions);
        console.log(`Payment failed email sent to ${email}`, info.messageId);
        return true;
    } catch (error) {
        console.error('Error sending payment failed email:', error);
        throw new Error('Failed to send payment failed email');
    }
}
}

module.exports = Email;