import DOMPurify from "isomorphic-dompurify"

/**
 * HTML sanitiser wrapper (KAR-533 / ASVS V1.8).
 *
 * Every user-provided HTML render path in the app MUST go through this
 * helper before being passed to a raw-HTML render prop. The function
 * is server-and-client safe — isomorphic-dompurify auto-detects.
 *
 * The configured allowlist matches a typical "rich text input" surface:
 * basic formatting + links + lists. It does NOT permit iframe, object,
 * script, custom attributes, or javascript: URLs.
 *
 * If a downstream use-case needs a wider allowlist, extend this file —
 * do not pass a custom config inline at every call site, because the
 * lint rule banning raw-HTML renders outside this module relies on a
 * single chokepoint.
 */
export function sanitizeHtml(input: string): string {
  if (typeof input !== "string") return ""
  return DOMPurify.sanitize(input, {
    USE_PROFILES: { html: true },
    ALLOWED_TAGS: [
      "p",
      "br",
      "strong",
      "em",
      "u",
      "code",
      "pre",
      "ul",
      "ol",
      "li",
      "a",
      "blockquote",
      "h1",
      "h2",
      "h3",
      "h4",
      "h5",
      "h6",
    ],
    ALLOWED_ATTR: ["href", "title", "target", "rel"],
    ALLOW_DATA_ATTR: false,
    FORBID_TAGS: ["script", "style", "iframe", "object", "embed", "form"],
    FORBID_ATTR: ["onerror", "onload", "onclick", "onmouseover", "style"],
  })
}
