import "server-only";
import nodemailer from "nodemailer";

type SendArgs = {
  to: string;
  subject: string;
  html: string;
  text?: string;
  from?: string;
};

function isConfigured(): boolean {
  return Boolean(process.env.MAIL_HOST && process.env.MAIL_HOST.length > 0);
}

let transporter: nodemailer.Transporter | null = null;

function getTransporter(): nodemailer.Transporter {
  if (!transporter) {
    transporter = nodemailer.createTransport({
      host: process.env.MAIL_HOST,
      port: Number(process.env.MAIL_PORT ?? 587),
      secure: process.env.MAIL_SECURE === "true",
      auth:
        process.env.MAIL_USER && process.env.MAIL_PASSWORD
          ? { user: process.env.MAIL_USER, pass: process.env.MAIL_PASSWORD }
          : undefined,
    });
  }
  return transporter;
}

/**
 * Versendet eine E-Mail. Ist kein SMTP konfiguriert (Entwicklung),
 * wird die Nachricht in die Server-Konsole geschrieben.
 */
export async function sendMail({ to, subject, html, text, from: fromArg }: SendArgs): Promise<void> {
  const from = fromArg ?? process.env.MAIL_FROM ?? "Avaria Team OS <no-reply@avaria.local>";

  if (!isConfigured()) {
    console.info(
      `\n[Mail – Dev-Modus, kein SMTP konfiguriert]\nAn: ${to}\nBetreff: ${subject}\n${
        text ?? html
      }\n`,
    );
    return;
  }

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