import nodemailer from "nodemailer";
import { env } from "../config/env.js";

let transporterPromise = null;

export function isMailConfigured() {
  return Boolean(env.smtpHost && env.smtpPort);
}

async function createTransporter() {
  if (!isMailConfigured()) return null;

  const transport = nodemailer.createTransport({
    host: env.smtpHost,
    port: env.smtpPort,
    secure: env.smtpSecure,
    requireTLS: env.smtpRequireTls,
    auth: env.smtpUser ? { user: env.smtpUser, pass: env.smtpPass } : undefined,
  });

  return transport;
}

async function getTransporter() {
  if (!transporterPromise) {
    transporterPromise = createTransporter();
  }

  return transporterPromise;
}

export async function sendMail({ to, subject, text, html, from }) {
  if (!isMailConfigured()) {
    return { ok: false, skipped: true, reason: "smtp_not_configured" };
  }

  const transporter = await getTransporter();
  if (!transporter) {
    return { ok: false, skipped: true, reason: "smtp_not_configured" };
  }

  const info = await transporter.sendMail({
    from: from || env.smtpFrom,
    to,
    subject,
    text,
    html,
  });

  return {
    ok: true,
    skipped: false,
    messageId: info.messageId,
    accepted: info.accepted,
    rejected: info.rejected,
  };
}
