import sanitizeHtml from "sanitize-html";
import { convert } from "html-to-text";

import { AppError } from "./errors.js";

export function sanitizeEmailHtml(input: string): string {
  const sanitized = sanitizeHtml(input, {
    allowedTags: sanitizeHtml.defaults.allowedTags.concat([
      "img",
      "table",
      "tbody",
      "thead",
      "tfoot",
      "tr",
      "td",
      "th",
      "style"
    ]),
    allowedAttributes: {
      "*": ["style", "class", "align"],
      a: ["href", "name", "target"],
      img: ["src", "srcset", "alt", "title", "width", "height"],
      td: ["colspan", "rowspan", "width", "height"],
      th: ["colspan", "rowspan", "width", "height"]
    },
    allowedSchemes: ["http", "https", "mailto", "data"]
  }).trim();

  if (!sanitized || !/<(html|table|div|section|body|p|h1|h2|h3|img)/i.test(sanitized)) {
    throw new AppError(400, "INVALID_HTML", "The provided HTML is empty or not valid email markup.");
  }

  return sanitized;
}

export function htmlToTextBody(html: string): string {
  return convert(html, {
    selectors: [
      { selector: "a", options: { hideLinkHrefIfSameAsText: true } },
      { selector: "img", format: "skip" }
    ],
    wordwrap: 120
  });
}
