import nodemailer from "nodemailer";

import { getSmtpRuntimeConfig } from "@/lib/app-settings";

let cachedTransporter: nodemailer.Transporter | null = null;
let cachedTransportKey: string | null = null;

async function getSmtpConfig() {
  const { host, port, secure, user, pass } = await getSmtpRuntimeConfig();

  if (!host || !user || !pass) {
    throw new Error("SMTP belum dikonfigurasi lengkap.");
  }

  return {
    host,
    port,
    secure,
    family: 4,
    auth: {
      user,
      pass
    },
    tls: {
      servername: host
    }
  };
}

async function getTransporter() {
  const config = await getSmtpConfig();
  const key = JSON.stringify(config);

  if (!cachedTransporter || cachedTransportKey !== key) {
    cachedTransporter = nodemailer.createTransport(config);
    cachedTransportKey = key;
  }
  return cachedTransporter;
}

export function resetMailerTransport() {
  cachedTransporter = null;
  cachedTransportKey = null;
}

export async function sendMail({
  to,
  subject,
  html,
  text
}: {
  to: string;
  subject: string;
  html: string;
  text: string;
}) {
  const transporter = await getTransporter();
  const { fromName, fromEmail, user } = await getSmtpRuntimeConfig();
  const resolvedFromEmail = fromEmail || user || "no-reply@abelbirdnest.local";
  const from = fromName ? `${fromName} <${resolvedFromEmail}>` : resolvedFromEmail;

  await transporter.sendMail({
    from,
    to,
    subject,
    html,
    text
  });
}
