const nodemailer = require('nodemailer');

class EmailService {
  static async getTransporter() {
    if (process.env.SMTP_HOST) {
      return nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: parseInt(process.env.SMTP_PORT || '587', 10),
        secure: process.env.SMTP_SECURE === 'true',
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASS,
        },
      });
    } else {
      // Fallback to Ethereal Email for testing if no SMTP is configured
      if (!this.testAccount) {
        try {
          this.testAccount = await nodemailer.createTestAccount();
          console.log(`[EmailService] Generated new Ethereal test account: ${this.testAccount.user}`);
        } catch (err) {
          console.error('[EmailService] Failed to create Ethereal test account, logging only:', err.message);
        }
      }

      if (this.testAccount) {
        return nodemailer.createTransport({
          host: 'smtp.ethereal.email',
          port: 587,
          secure: false,
          auth: {
            user: this.testAccount.user,
            pass: this.testAccount.pass,
          },
        });
      }

      return null;
    }
  }

  static async sendPasswordRecovery(email, tempPassword, loginLink) {
    const transporter = await this.getTransporter();
    
    const subject = 'NextGen LMS - Temporary Password Recovery';
    const htmlContent = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 10px;">
        <h2 style="color: #002147; text-align: center;">NextGen LMS Security</h2>
        <p>Hello,</p>
        <p>A request was made to recover the password for your NextGen LMS account associated with this email address.</p>
        <p>We have reset your password to a temporary password:</p>
        <div style="margin: 20px 0; padding: 15px; background-color: #f4f6f9; border-left: 5px solid #002147; font-family: monospace; font-size: 18px; font-weight: bold; text-align: center; letter-spacing: 1px;">
          ${tempPassword}
        </div>
        <p>Use the link below to access the gateway and login with this temporary password. We strongly recommend changing your password once logged in via your user profile.</p>
        <div style="margin: 30px 0; text-align: center;">
          <a href="${loginLink}" style="background-color: #002147; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;">Go to Login Gateway</a>
        </div>
        <p>If you did not request a password recovery, please contact your systems administrator immediately.</p>
        <hr style="border: none; border-top: 1px solid #eeeeee; margin: 30px 0;" />
        <p style="font-size: 11px; color: #999999; text-align: center;">NextGen LMS Intelligence &copy; 2026</p>
      </div>
    `;

    if (!transporter) {
      console.log('--- EMAIL SENDING SIMULATED (No SMTP / Ethereal connection) ---');
      console.log(`To: ${email}`);
      console.log(`Subject: ${subject}`);
      console.log(`Temporary Password: ${tempPassword}`);
      console.log(`Login Link: ${loginLink}`);
      console.log('--------------------------------------------------------------');
      return { success: true, simulated: true };
    }

    const from = process.env.SMTP_FROM || (this.testAccount ? `"${this.testAccount.user}" <${this.testAccount.user}>` : '"NextGen Support" <support@nextgen.edu>');
    const info = await transporter.sendMail({
      from,
      to: email,
      subject,
      html: htmlContent,
    });

    if (this.testAccount) {
      const previewUrl = nodemailer.getTestMessageUrl(info);
      console.log(`[EmailService] Ethereal Email sent. Preview URL: ${previewUrl}`);
      return { success: true, previewUrl };
    }

    console.log(`[EmailService] Real recovery email sent to ${email}`);
    return { success: true };
  }
}

EmailService.testAccount = null;

module.exports = EmailService;
