/**
 * Minimal server-side HTML stripping for plain-text inputs.
 *
 * Comment bodies are plain text + mention tokens (@[Name](id)).
 * Any HTML tags injected by a malicious actor are removed here before
 * persistence so that even consumers that skip the client-side DOMPurify
 * step (email notifications, PDF reports, AI assistant responses) are safe.
 *
 * Algorithm:
 *   1. Strip all HTML tags.
 *   2. Decode a small allow-list of HTML entities to their UTF-8 equivalents.
 *
 * This is intentionally minimal — do not extend it to allow any tags.
 */

const HTML_ENTITIES: Record<string, string> = {
  "&amp;": "&",
  "&lt;": "<",
  "&gt;": ">",
  "&quot;": '"',
  "&#39;": "'",
  "&apos;": "'",
  "&nbsp;": " ",
};

export function stripHtml(input: string): string {
  // Remove all HTML/XML tags (including self-closing and multi-line)
  const tagStripped = input.replace(/<[^>]*>/g, "");
  // Decode common HTML entities
  return tagStripped.replace(
    /&(?:amp|lt|gt|quot|#39|apos|nbsp);/g,
    (entity) => HTML_ENTITIES[entity] ?? entity,
  );
}
