/**
 * Email sender — thin wrapper around nodemailer used by the
 * EmailMagicLinkProvider (DC-047).
 *
 * This is deliberately separate from src/managers/notification-manager.js
 * which sends broadcast notifications to operator-configured channels.
 * Authentication emails go to a dynamic recipient (the user who just typed
 * their address into the login form), so they share the SMTP *config* but
 * not the recipient model.
 *
 * Config shape: same as notificationManager.config.providers.email:
 *   { enabled, host, port, secure, username, password, from }
 * Reuses the existing settings — operators configure SMTP once, both the
 * notification system and the auth system use it.
 */

const nodemailer = require('nodemailer');

/**
 * Whether the SMTP config is present enough to attempt sending.
 * Returns false if host or from is missing OR if enabled is explicitly false.
 */
function isConfigured(emailConfig) {
  if (!emailConfig || typeof emailConfig !== 'object') return false;
  if (emailConfig.enabled === false) return false;
  return Boolean(emailConfig.host && emailConfig.from);
}

/**
 * Send a single email. Caller provides the recipient, subject, body.
 *
 * @param {Object} emailConfig  The providers.email config object
 * @param {string} to            Recipient address (RFC-5322)
 * @param {string} subject       Subject line
 * @param {string} text          Plain-text body
 * @param {string} [html]        Optional HTML body
 * @returns {Promise<{messageId: string}>} nodemailer send result
 * @throws Error on SMTP failure (caller decides how to react)
 */
async function sendEmail(emailConfig, to, subject, text, html) {
  if (!emailConfig || !emailConfig.host || !emailConfig.from) {
    throw new Error('SMTP not configured: email provider missing host or from');
  }
  const transporter = nodemailer.createTransport({
    host: emailConfig.host,
    port: parseInt(emailConfig.port, 10) || 587,
    secure: Boolean(emailConfig.secure),
    auth: emailConfig.username ? {
      user: emailConfig.username,
      pass: emailConfig.password,
    } : undefined,
    // Keep TLS handshake fast — auth flows depend on this returning inside
    // ~5s. SMTP servers that hang can stall login UX.
    tls: {
      rejectUnauthorized: process.env.NODE_ENV === 'production',
    },
  });
  return transporter.sendMail({
    from: emailConfig.from,
    to,
    subject,
    text,
    html,
  });
}

module.exports = { isConfigured, sendEmail };
