import { tryGetDocument } from '../../try-get-document';
import { serializeFragment } from '../utils/serialize-fragment';
/**
 * Main sanitization engine.
 *
 * Responsible for:
 * - Parsing HTML
 * - Delegating sanitization to strategy
 * - Serializing safe output
 */
export class HtmlSanitizer {
  /**
   * Sanitizes the given string using the provided sanitization strategy.
   *
   * This is the single entry point for HTML sanitization.
   * Always returns a safe string for DOM insertion.
   *
   * @param {string} input - Raw string input to be sanitized.
   * @param {SanitizeStrategy} strategy - Sanitization strategy to apply.
   * @returns { string } Sanitized string safe for rendering.
   */
  sanitize(input, strategy) {
    if (!input || input.trim() === '') {
      return '';
    }
    const doc = tryGetDocument();
    if (!doc)
      return '';
    const parser = new DOMParser();
    const parsed = parser.parseFromString(input, 'text/html');
    const fragment = doc.createDocumentFragment();
    parsed.body.childNodes.forEach((node) => {
      const clean = strategy.execute(node, doc);
      if (clean)
        fragment.appendChild(clean);
    });
    return serializeFragment(fragment, doc);
  }
}
