import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT || 587),
  secure: process.env.SMTP_SECURE === "true",
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
});

// Nur HTML ohne Text-Alternative zu verschicken ist ein Spamfilter-Signal
// (echte Absender liefern praktisch immer ein multipart/alternative mit
// Text-Fallback) — statt einer echten HTML-Parser-Bibliothek reicht hier ein
// einfacher Tag-Strip, weil unser emailShell-Template alle relevanten Inhalte
// (Überschrift, Text, Button-Beschriftung, Button-URL als sichtbarer Text,
// Footer) ohnehin schon als reinen Text-Inhalt enthält, nur in Tags verpackt.
function htmlToPlainText(html: string): string {
  return html
    .replace(/<style[\s\S]*?<\/style>/gi, "")
    .replace(/<\/(p|div|tr|h1|h2|h3|table)>/gi, "\n")
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<[^>]+>/g, "")
    .replace(/&nbsp;/g, " ")
    .replace(/&amp;/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/[ \t]+/g, " ")
    .split("\n")
    .map((line) => line.trim())
    .join("\n")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
}

export async function sendMail(to: string, subject: string, html: string) {
  await transporter.sendMail({
    from: process.env.MAIL_FROM || process.env.SMTP_USER,
    to,
    subject,
    html,
    text: htmlToPlainText(html),
  });
}

// Für optionale Benachrichtigungs-Mails (Wiedervorlage, Erinnerungen,
// Prämien — siehe Client.emailNotificationsEnabled) statt sendMail direkt —
// kritische Transaktions-Mails (Rechnung, Zahlungserinnerung, Registrierung)
// nutzen weiterhin sendMail() direkt und ignorieren diese Einstellung bewusst.
export async function sendMailIfEnabled(clientId: string, to: string, subject: string, html: string) {
  const { connectDB } = await import("@/lib/db");
  const { Client } = await import("@/models/Client");
  await connectDB();
  const client = await Client.findById(clientId).select("emailNotificationsEnabled").lean();
  if (client && client.emailNotificationsEnabled === false) return;
  await sendMail(to, subject, html);
}
