import nodemailer from "nodemailer";
import { config } from "../config/env";
import { getSystemSettings } from "./system-settings";

// Default transport: local sendmail (unchanged prod behaviour). When
// SMTP_HOST is set in the environment, switch to an SMTP transport instead —
// this is purely opt-in: with the var absent, behaviour is identical to before.
// (We read process.env directly here so no .env edit is required to enable it.)
function buildTransporter() {
  const host = process.env.SMTP_HOST;
  if (host) {
    const port = Number(process.env.SMTP_PORT) || 587;
    const user = process.env.SMTP_USER;
    const pass = process.env.SMTP_PASS;
    // secure=true for implicit TLS (465), STARTTLS otherwise.
    const secure =
      process.env.SMTP_SECURE === "true" ||
      process.env.SMTP_SECURE === "1" ||
      port === 465;
    return nodemailer.createTransport({
      host,
      port,
      secure,
      auth: user && pass ? { user, pass } : undefined,
    });
  }
  return nodemailer.createTransport({
    sendmail: true,
    newline: "unix",
    path: "/usr/sbin/sendmail",
  });
}

const transporter = buildTransporter();

export async function sendMail(
  to: string,
  subject: string,
  html: string,
): Promise<boolean> {
  // Guard against an empty/blank recipient — nodemailer would either throw or
  // silently produce an envelope with no recipient.
  if (typeof to !== "string" || to.trim() === "") {
    console.error("Mailer error: missing or empty recipient");
    return false;
  }

  const settings = await getSystemSettings();
  const from =
    settings.smtp_from ||
    config.email.smtpFrom ||
    config.email.contactFrom ||
    "noreply@example.com";
  const fromName =
    settings.smtp_from_name || config.email.smtpFromName || "System";

  try {
    await transporter.sendMail({
      from: { name: fromName, address: from },
      to,
      subject,
      html,
    });
    return true;
  } catch (err) {
    console.error(`Mailer error: failed to send to ${to}:`, err);
    return false;
  }
}
