const nodemailer = require('nodemailer');

let transporter = null;

function initializeTransporter() {
  if (transporter) return transporter;

  transporter = nodemailer.createTransport({
    host: process.env.EMAIL_HOST || 'localhost',
    port: process.env.EMAIL_PORT || 587,
    secure: false,
    auth: process.env.EMAIL_USER ? {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASS
    } : undefined
  });

  return transporter;
}

async function sendCertificateEmail(email, learnerName, certificateUrl) {
  try {
    const transport = initializeTransporter();

    const mailOptions = {
      from: process.env.EMAIL_USER || 'noreply@ces-training.com',
      to: email,
      subject: 'Your PCA Certification Certificate',
      html: `
        <h2>Congratulations!</h2>
        <p>Dear ${learnerName},</p>
        <p>You have successfully completed the Connecticut Elderly Services PCA Certification Training Program.</p>
        <p>Your certificate has been generated and is available at: <a href="${certificateUrl}">Download Certificate</a></p>
        <p>Thank you for completing this important training.</p>
        <p>Connecticut Elderly Services</p>
      `
    };

    await transport.sendMail(mailOptions);
    return true;
  } catch (err) {
    console.error('Email send error:', err);
    // Don't throw - email is optional
    return false;
  }
}

module.exports = {
  sendCertificateEmail
};
