import nodemailer from "nodemailer";
import type { Transporter } from "nodemailer";
import type { EmailPayload } from "./types";

// ── Singleton transport (lazy init, same pattern as prisma) ──

const globalForEmail = globalThis as unknown as {
  emailTransport: Transporter | undefined;
};

function getTransport(): Transporter {
  if (globalForEmail.emailTransport) return globalForEmail.emailTransport;

  const host = process.env.BREVO_SMTP_HOST ?? "smtp-relay.brevo.com";
  const port = parseInt(process.env.BREVO_SMTP_PORT ?? "587", 10);
  const user = process.env.BREVO_SMTP_USER ?? "";
  const pass = process.env.BREVO_SMTP_PASS ?? "";

  if (!user || !pass) {
    throw new Error(
      "BREVO_SMTP_USER and BREVO_SMTP_PASS must be set for email notifications",
    );
  }

  const transport = nodemailer.createTransport({
    host,
    port,
    secure: false, // STARTTLS on port 587
    auth: { user, pass },
  });

  if (process.env.NODE_ENV !== "production") {
    globalForEmail.emailTransport = transport;
  }

  return transport;
}

/**
 * Send a single email via Brevo SMTP relay.
 */
export async function sendEmail(payload: EmailPayload): Promise<void> {
  const fromEmail =
    process.env.NOTIFICATION_FROM_EMAIL ?? "noreply@beletage.ro";
  const fromName = process.env.NOTIFICATION_FROM_NAME ?? "ArchiTools";

  const transport = getTransport();

  await transport.sendMail({
    from: `"${fromName}" <${fromEmail}>`,
    to: payload.to,
    subject: payload.subject,
    html: payload.html,
  });
}
