import nodemailer from "nodemailer";
import { env } from "../../config/env.js";
import { decrypt } from "../crypto.js";
import { execute, one, pool, query, type Db } from "../db/db.js";

export interface Mail { to: string; subject: string; text: string; template: string; projectId?: string; replyTo?: string | null; dedupe?: string; entityType?: string; entityId?: string }
const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!);
/** The same line as in V1 and at the bottom of every page. */
const developer = Boolean(env.DEVELOPER_NAME && (env.DEVELOPER_URL || env.DEVELOPER_EMAIL));
/** Writes to the outbox in the caller's transaction. One message per person, never a shared To: line. */
export async function queueMail(db: Db, m: Mail): Promise<string> {
  const body = m.text.split("\n").map((l) => (/^https?:\/\/\S+$/.test(l) ? `<p><a href="${esc(l)}" style="color:#0f5e70">${esc(l)}</a></p>` : `<p>${esc(l)}</p>`)).join("");
  const html = `<div style="font-family:Arial,sans-serif;font-size:15px;line-height:1.5;color:#1d2b30;max-width:600px"><div style="background:#0f5e70;color:#fff;padding:14px 20px;font-weight:bold;border-radius:8px 8px 0 0">PBPS MIS</div><div style="border:1px solid #ddd8cc;border-top:0;padding:10px 20px 16px;border-radius:0 0 8px 8px">${body}</div>${developer ? `<p style="font-size:12px;color:#5c6b70">Developer <a href="${esc(env.DEVELOPER_URL ?? `mailto:${env.DEVELOPER_EMAIL}`)}" style="color:#0f5e70">${esc(env.DEVELOPER_NAME!)}</a>${env.DEVELOPER_EMAIL ? ` &middot; <a href="mailto:${esc(env.DEVELOPER_EMAIL)}" style="color:#0f5e70">${esc(env.DEVELOPER_EMAIL)}</a>` : ""}</p>` : ""}</div>`;
  const text = developer ? `${m.text}\n\n--\nDeveloper ${env.DEVELOPER_NAME} ${env.DEVELOPER_URL ?? env.DEVELOPER_EMAIL}` : m.text;
  const r = await execute(db, `INSERT INTO email_outbox (project_id, to_email, reply_to, subject, html_body, text_body, template_key, entity_type, entity_id, dedupe_key, status, next_attempt_at) VALUES (?,?,?,?,?,?,?,?,?,?,'queued',UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`,
    [m.projectId ?? null, m.to, m.replyTo ?? null, m.subject.replace(/[\r\n]+/g, " ").slice(0, 190), html, text, m.template, m.entityType ?? null, m.entityId ?? null, m.dedupe ?? null]);
  return String(r.insertId);
}
async function transport() {
  const s = await one(pool, "SELECT * FROM mail_settings WHERE id=1");
  if (!s) return null;
  const t = nodemailer.createTransport({ host: s["smtp_host"], port: s["smtp_port"], secure: s["smtp_secure"] === "tls", requireTLS: s["smtp_secure"] === "starttls", ...(s["smtp_user"] ? { auth: { user: s["smtp_user"], pass: s["smtp_password_enc"] ? decrypt(s["smtp_password_enc"]) : "" } } : {}) });
  return { t, from: { name: s["from_name"] as string, address: s["from_email"] as string }, enabled: Boolean(s["is_enabled"]) };
}
/** Nothing leaves this machine unless MAIL_DELIVERY=on, so a copy of real data can never email real people by accident. */
export async function deliverOutbox(limit = 20): Promise<number> {
  if (env.MAIL_DELIVERY !== "on") return 0;
  const tr = await transport();
  if (!tr?.enabled) return 0;
  const rows = await query(pool, "SELECT * FROM email_outbox WHERE status='queued' AND next_attempt_at<=UTC_TIMESTAMP(3) ORDER BY id LIMIT ?", [limit]);
  let sent = 0;
  for (const m of rows) {
    const mine = await execute(pool, "UPDATE email_outbox SET status='sending', attempts=attempts+1 WHERE id=? AND status='queued'", [m["id"]]);
    if (!mine.affectedRows) continue;
    try {
      const r = await tr.t.sendMail({ from: tr.from, to: m["to_email"], subject: m["subject"], text: m["text_body"], html: m["html_body"], ...(m["reply_to"] ? { replyTo: m["reply_to"] } : {}) });
      await execute(pool, "UPDATE email_outbox SET status='sent', sent_at=UTC_TIMESTAMP(3), provider_message_id=?, last_error=NULL WHERE id=?", [String(r.messageId).slice(0, 190), m["id"]]);
      sent++;
    } catch (error) {
      const tries = Number(m["attempts"]) + 1;
      await execute(pool, "UPDATE email_outbox SET status=?, last_error=?, next_attempt_at=UTC_TIMESTAMP(3)+INTERVAL ? MINUTE WHERE id=?", [tries >= 6 ? "dead" : "queued", (error as Error).message.slice(0, 450), 2 ** tries, m["id"]]);
    }
  }
  return sent;
}
