import nodemailer from "nodemailer";

import type { AlertMailGroup } from "@/services/alertes-mail.service";

const GROUP_LABELS: Record<AlertMailGroup, string> = {
  direction: "Direction",
  adm: "Administratif",
  cisp: "CISP",
  logistique: "Logistique",
  atelier: "Atelier",
};

type TestMailConfiguration = {
  recipients: string[];
  smtpUser: string;
  smtpAppPassword: string;
};

function isValidEmail(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}

function escapeHtml(value: string) {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#039;");
}

function getTestMailConfiguration(): TestMailConfiguration {
  if (process.env.MAIL_TEST_ENABLED?.toLowerCase() !== "true") {
    throw new Error("TEST_MAIL_DISABLED");
  }

  const recipients = [
    ...new Set(
      (process.env.MAIL_TEST_RECIPIENTS ?? "")
        .split(/[;,]/)
        .map((email) => email.trim().toLowerCase())
        .filter((email) => isValidEmail(email)),
    ),
  ];

  const smtpUser = process.env.MAIL_TEST_SMTP_USER
    ?.trim()
    .toLowerCase();

  const smtpAppPassword = process.env.MAIL_TEST_SMTP_APP_PASSWORD
    ?.replace(/\s+/g, "")
    .trim();

  if (recipients.length === 0) {
    throw new Error("TEST_MAIL_INVALID_RECIPIENT");
  }

  if (!smtpUser || !isValidEmail(smtpUser) || !smtpAppPassword) {
    throw new Error("TEST_MAIL_INVALID_SMTP_CONFIGURATION");
  }

  return {
    recipients,
    smtpUser,
    smtpAppPassword,
  };
}

function buildAnonymizedTestMail(group: AlertMailGroup) {
  const groupLabel = GROUP_LABELS[group];
  const subject = `[TEST] RH Connect - Alertes RH - ${groupLabel}`;
  const sentAt = new Date();
  const formattedDate = new Intl.DateTimeFormat("fr-FR", {
    dateStyle: "full",
    timeStyle: "medium",
    timeZone: "Europe/Paris",
  }).format(sentAt);

  const html = `<!doctype html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <title>${escapeHtml(subject)}</title>
  </head>
  <body style="margin:0;background:#f8fafc;font-family:Arial,sans-serif;color:#0f172a;">
    <div style="max-width:760px;margin:0 auto;padding:24px;">
      <div style="background:#fff;border:1px solid #cbd5e1;padding:24px;">
        <div style="display:inline-block;margin-bottom:18px;padding:6px 10px;background:#fef3c7;color:#92400e;font-size:12px;font-weight:700;">
          TEST ANONYMISÉ — AUCUNE DONNÉE RH RÉELLE
        </div>

        <h1 style="margin:0 0 6px;color:#0369a1;font-size:26px;">
          Alertes Ressources Humaines
        </h1>
        <p style="margin:0 0 26px;color:#64748b;">
          Groupe destinataire testé : ${escapeHtml(groupLabel)}
        </p>

        <section style="margin-bottom:24px;">
          <h2 style="margin:0 0 10px;font-size:20px;">Exemple d'alerte standard</h2>
          <ul style="margin:0;padding-left:24px;color:#475569;">
            <li style="margin-bottom:8px;">
              SALARIÉ TEST (Secteur fictif) : document fictif à renouveler le 31/12/2030
            </li>
          </ul>
        </section>

        <section style="margin-bottom:24px;">
          <h2 style="margin:0 0 10px;font-size:20px;">Exemple d'alerte urgente</h2>
          <ul style="margin:0;padding-left:24px;color:#b91c1c;font-weight:700;">
            <li style="margin-bottom:8px;">
              SALARIÉ TEST (Secteur fictif) : exemple d'alerte urgente
            </li>
          </ul>
        </section>

        <p style="margin:28px 0 0;padding-top:18px;border-top:1px solid #e2e8f0;color:#64748b;font-size:13px;">
          Mail de test généré par RH Connect le ${escapeHtml(formattedDate)}.
          Si tu reçois ce message, la connexion SMTP et le rendu HTML fonctionnent.
        </p>
      </div>
    </div>
  </body>
</html>`;

  const text = [
    "TEST ANONYMISÉ — AUCUNE DONNÉE RH RÉELLE",
    "",
    "Alertes Ressources Humaines",
    `Groupe destinataire testé : ${groupLabel}`,
    "",
    "Exemple d'alerte standard :",
    "SALARIÉ TEST (Secteur fictif) : document fictif à renouveler le 31/12/2030",
    "",
    "Exemple d'alerte urgente :",
    "SALARIÉ TEST (Secteur fictif) : exemple d'alerte urgente",
    "",
    `Mail de test généré par RH Connect le ${formattedDate}.`,
  ].join("\n");

  return {
    subject,
    html,
    text,
  };
}

export async function sendAnonymizedAlertTestMail(group: AlertMailGroup) {
  const configuration = getTestMailConfiguration();
  const mail = buildAnonymizedTestMail(group);

  const transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 465,
    secure: true,
    auth: {
      user: configuration.smtpUser,
      pass: configuration.smtpAppPassword,
    },
    connectionTimeout: 15_000,
    greetingTimeout: 10_000,
    socketTimeout: 20_000,
  });

  const result = await transporter.sendMail({
    from: `"RH Connect - Test" <${configuration.smtpUser}>`,
    to: configuration.recipients,
    subject: mail.subject,
    text: mail.text,
    html: mail.html,
    disableFileAccess: true,
    disableUrlAccess: true,
  });

  return {
    messageId: result.messageId,
    recipient: configuration.recipients,
    subject: mail.subject,
    accepted: result.accepted.map(String),
    rejected: result.rejected.map(String),
    sentAt: new Date().toISOString(),
    anonymized: true,
  };
}
