const nodemailer = require('nodemailer');

function getSmtpConfig() {
  const server = process.env.CLOUDRON_MAIL_SMTP_SERVER || process.env.MAIL_SMTP_SERVER;
  const port = process.env.CLOUDRON_MAIL_SMTP_PORT || process.env.MAIL_SMTP_PORT || '587';
  const username = process.env.CLOUDRON_MAIL_SMTP_USERNAME || process.env.MAIL_SMTP_USERNAME;
  const password = process.env.CLOUDRON_MAIL_SMTP_PASSWORD || process.env.MAIL_SMTP_PASSWORD;
  const from = process.env.CLOUDRON_MAIL_FROM || process.env.MAIL_FROM || username;

  if (!server) return null;
  return { host: server, port: Number(port), secure: Number(port) === 465, auth: (username && password) ? { user: username, pass: password } : undefined, from };
}

let _transporter = null;

function getTransporter() {
  if (_transporter) return _transporter;
  const config = getSmtpConfig();
  if (!config) return null;
  _transporter = nodemailer.createTransport({
    host: config.host,
    port: config.port,
    secure: config.secure,
    auth: config.auth,
    tls: { rejectUnauthorized: false },
  });
  _transporter._from = config.from;
  return _transporter;
}

async function sendMail({ to, subject, html, text }) {
  const transporter = getTransporter();
  if (!transporter) throw new Error('SMTP not configured');
  return transporter.sendMail({ from: transporter._from, to, subject, html, text });
}

module.exports = { sendMail, getSmtpConfig };
