/**
 * Email sending via SMTP (nodemailer). Every send takes an optional per-tenant
 * SMTP config; if a tenant hasn't set one, we fall back to the platform SMTP_*
 * env vars. If neither exists, emails are logged to the console (dev mode).
 */
import nodemailer from "nodemailer";

// Cache one transport per distinct SMTP config (keyed by host+port+user).
const transports = new Map();

function envSmtp() {
  return process.env.SMTP_HOST
    ? {
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT || 587),
        secure: (process.env.SMTP_SECURE || "false").toLowerCase() === "true",
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
        from: process.env.SMTP_FROM,
      }
    : null;
}

function transport(smtp) {
  const cfg = smtp && smtp.host ? smtp : envSmtp();
  if (!cfg) return null;
  const key = `${cfg.host}:${cfg.port}:${cfg.user || ""}`;
  if (!transports.has(key)) {
    transports.set(key, nodemailer.createTransport({
      host: cfg.host,
      port: Number(cfg.port || 587),
      secure: !!cfg.secure,
      auth: cfg.user ? { user: cfg.user, pass: cfg.pass } : undefined,
      connectionTimeout: 10000, greetingTimeout: 8000, socketTimeout: 15000,
    }));
  }
  return { t: transports.get(key), from: cfg.from || cfg.user || "no-reply@localhost" };
}

export async function sendMail(smtp, { to, subject, text, html, replyTo }) {
  const built = transport(smtp);
  if (!built) {
    console.log(`\n[mail:dev] (no SMTP configured — logging instead of sending)\n  to: ${to}\n  subject: ${subject}\n  ${text}\n`);
    return { delivered: false, dev: true };
  }
  await built.t.sendMail({ from: built.from, to, subject, text, html, replyTo });
  return { delivered: true };
}

/** Email a one-time verification code to a prospective chat user. */
export function sendVerificationCode(smtp, email, code, brand) {
  brand = brand || "Support";
  return sendMail(smtp, {
    to: email,
    subject: `Your ${brand} verification code: ${code}`,
    text: `Your verification code is ${code}. It expires in 10 minutes.`,
    html: verifyHtml(brand, code),
  });
}

/** Email a password-reset link to a tenant admin. */
export function sendPasswordReset(smtp, email, link) {
  return sendMail(smtp, {
    to: email,
    subject: "Reset your chat dashboard password",
    text: `Reset your password using this link (valid for 1 hour):\n${link}\n\nIf you didn't request this, you can ignore this email.`,
    html: `<div style="font-family:-apple-system,Segoe UI,Roboto,sans-serif;max-width:440px;margin:0 auto;padding:28px">
      <h2 style="margin:0 0 8px;color:#1c1c2e">Reset your password</h2>
      <p style="color:#6b6b80;margin:0 0 22px">Click below to set a new password. This link expires in 1 hour.</p>
      <a href="${link}" style="display:inline-block;background:#6366f1;color:#fff;text-decoration:none;padding:12px 22px;border-radius:10px;font-weight:600">Reset password</a>
      <p style="color:#9a9ab0;font-size:13px;margin-top:22px">If you didn't request this, you can safely ignore this email.</p>
    </div>`,
  });
}

/** Notify a tenant's admin that a new visitor started a chat. */
export function sendLeadNotification(smtp, { to, name, email }) {
  if (!to) return Promise.resolve({ delivered: false });
  const when = new Date().toISOString();
  return sendMail(smtp, {
    to,
    replyTo: email,
    subject: `New chat lead: ${name} <${email}>`,
    text: `A new visitor verified their email and started a chat.\n\nName:  ${name}\nEmail: ${email}\nTime:  ${when}`,
    html: leadHtml(name, email, when),
  });
}

function verifyHtml(brand, code) {
  return `<div style="font-family:-apple-system,Segoe UI,Roboto,sans-serif;max-width:440px;margin:0 auto;padding:28px">
    <h2 style="margin:0 0 6px;color:#1c1c2e">Verify your email</h2>
    <p style="color:#6b6b80;margin:0 0 22px">Enter this code in the chat to get started with ${escapeHtml(brand)}.</p>
    <div style="font-size:34px;font-weight:800;letter-spacing:10px;color:#6366f1;background:#f4f3fb;border-radius:14px;padding:18px;text-align:center">${code}</div>
    <p style="color:#9a9ab0;font-size:13px;margin-top:22px">This code expires in 10 minutes. If you didn't request it, you can ignore this email.</p>
  </div>`;
}

function leadHtml(name, email, when) {
  return `<div style="font-family:-apple-system,Segoe UI,Roboto,sans-serif;max-width:460px;margin:0 auto;padding:24px">
    <h2 style="margin:0 0 14px;color:#1c1c2e">New chat lead</h2>
    <table style="width:100%;border-collapse:collapse;font-size:14px;color:#1c1c2e">
      <tr><td style="padding:8px 0;color:#6b6b80;width:80px">Name</td><td style="padding:8px 0;font-weight:600">${escapeHtml(name)}</td></tr>
      <tr><td style="padding:8px 0;color:#6b6b80">Email</td><td style="padding:8px 0;font-weight:600"><a href="mailto:${escapeHtml(email)}">${escapeHtml(email)}</a></td></tr>
      <tr><td style="padding:8px 0;color:#6b6b80">Time</td><td style="padding:8px 0">${when}</td></tr>
    </table>
  </div>`;
}

function escapeHtml(s) {
  return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
