import sanitizeHtmlLib from "sanitize-html";

// As campanhas são documentos HTML completos (DOCTYPE + html/head/body) com estilos
// inline extensivos (tabelas de e-mail), então a allowlist padrão da lib (pensada para
// fragmentos de rich text) precisa ser estendida para não descartar a estrutura do e-mail.
const ALLOWED_TAGS = [
  ...sanitizeHtmlLib.defaults.allowedTags,
  "html",
  "head",
  "body",
  "meta",
  "title",
  "style",
  "base",
  "img",
  "font",
  "center",
];

const ALLOWED_ATTRIBUTES: Record<string, string[]> = {
  ...sanitizeHtmlLib.defaults.allowedAttributes,
  "*": ["style", "class", "id", "align", "valign", "width", "height", "bgcolor", "color", "border", "lang"],
  meta: ["charset", "name", "content", "http-equiv"],
  table: ["role", "cellspacing", "cellpadding"],
  td: ["colspan", "rowspan"],
  th: ["colspan", "rowspan"],
  font: ["face", "size"],
};

/** Sanitiza o HTML de uma campanha antes de persistir no banco. */
export function sanitizeHtml(html: string): string {
  return sanitizeHtmlLib(html, {
    allowedTags: ALLOWED_TAGS,
    allowedAttributes: ALLOWED_ATTRIBUTES,
    // Uploads de imagem no editor geram data URIs (FileReader.readAsDataURL).
    allowedSchemes: [...sanitizeHtmlLib.defaults.allowedSchemes, "data"],
    allowVulnerableTags: true,
  });
}
