import { Injectable } from '@nestjs/common';
import sanitizeHtml from 'sanitize-html';

/**
 * Whitelist-based HTML sanitizer for inquiry messages.
 *
 * Defense-in-depth complement to the global SanitizeInputMiddleware:
 * - the global middleware strips ALL tags from incoming HTTP request bodies,
 * - this service runs at the application layer right before persistence,
 *   guaranteeing safe content even if a future code path (queue replay,
 *   internal command dispatch, import job) bypasses the HTTP middleware.
 *
 * Allow-list is intentionally minimal per TEC-2929:
 *   <b>, <i>, <br>, <p>, <a> (links forced to rel=noopener noreferrer nofollow,
 *   target=_blank, http(s) only).
 *
 * Everything else (including <script>, <iframe>, <img onerror=...>, inline
 * event handlers, javascript: URLs, etc.) is dropped.
 */
@Injectable()
export class SanitizeHtmlService {
  private static readonly OPTIONS: sanitizeHtml.IOptions = {
    allowedTags: ['b', 'i', 'br', 'p', 'a'],
    allowedAttributes: {
      a: ['href', 'rel', 'target'],
    },
    allowedSchemes: ['http', 'https', 'mailto', 'tel'],
    allowedSchemesAppliedToAttributes: ['href'],
    allowProtocolRelative: false,
    disallowedTagsMode: 'discard',
    transformTags: {
      a: sanitizeHtml.simpleTransform('a', {
        rel: 'noopener noreferrer nofollow',
        target: '_blank',
      }),
    },
  };

  /**
   * Sanitize a single string of inquiry message content.
   *
   * Returns the sanitized string. Always returns a string (never throws on
   * non-string input — empty string is returned for null/undefined to keep
   * call sites simple).
   */
  sanitizeInquiryMessage(input: string | null | undefined): string {
    if (typeof input !== 'string' || input.length === 0) {
      return '';
    }
    return sanitizeHtml(input, SanitizeHtmlService.OPTIONS);
  }
}
