// src/shared/lib/sanitize.ts
// XSS Protection utility for sanitizing HTML content

/**
 * Allowed HTML tags for rich text content
 * These are safe tags that can be used in notes and comments
 */
const ALLOWED_TAGS = [
  'p', 'br', 'b', 'i', 'u', 'em', 'strong',
  'a', 'ul', 'ol', 'li',
  'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  'blockquote', 'code', 'pre',
];

/**
 * Sanitize HTML string by removing dangerous tags and attributes
 * @param html - HTML string to sanitize
 * @returns Sanitized HTML string
 */
export function sanitizeHtml(html: string): string {
  if (!html || typeof html !== 'string') {
    return '';
  }

  // Remove script tags and content
  let sanitized = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');

  // Remove iframe tags
  sanitized = sanitized.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '');

  // Remove object tags
  sanitized = sanitized.replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi, '');

  // Remove embed tags
  sanitized = sanitized.replace(/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi, '');

  // Remove style tags with content
  sanitized = sanitized.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '');

  // Remove on* event handlers from all tags
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*[^\s>]*/gi, '');

  // Remove javascript: protocol
  sanitized = sanitized.replace(/javascript:/gi, '');
  sanitized = sanitized.replace(/data:/gi, '');

  // Remove vbscript:
  sanitized = sanitized.replace(/vbscript:/gi, '');

  return sanitized;
}

/**
 * Sanitize plain text by removing HTML tags
 * @param text - Plain text string to sanitize
 * @returns Sanitized plain text string
 */
export function sanitizeText(text: string): string {
  if (!text || typeof text !== 'string') {
    return '';
  }

  // Remove all HTML tags
  return text.replace(/<[^>]*>/g, '');
}

/**
 * Check if HTML contains only allowed tags
 * @param html - HTML string to check
 * @returns true if HTML contains only allowed tags
 */
export function isSafeHtml(html: string): boolean {
  if (!html || typeof html !== 'string') {
    return false;
  }

  // Check for dangerous tags
  const dangerousTags = ['script', 'iframe', 'object', 'embed', 'style'];
  const lowerHtml = html.toLowerCase();

  for (const tag of dangerousTags) {
    if (lowerHtml.includes(`<${tag}`)) {
      return false;
    }
  }

  return true;
}

/**
 * Strip <app-mention> tags and extract user names for tooltips
 * Replaces <app-mention user-id="UUID" user-name="Name">Name</app-mention>
 * with just "Name" for display in tooltips
 *
 * @param html - HTML string with <app-mention> tags
 * @returns Plain text string with mention tags replaced by user names
 */
export function stripMentionTags(html: string): string {
  if (!html || typeof html !== 'string') {
    return '';
  }

  // Find all <app-mention> tags and replace with user-name attribute value
  // Pattern: <app-mention user-id="..." user-name="Name">...</app-mention>
  let result = html.replace(/<app-mention[^>]*user-name="([^"]*)"[^>]*>.*?<\/app-mention>/gi, '$1');

  // Decode HTML entities: &nbsp;, &amp;, &quot;, &lt;, &gt;
  result = result
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&quot;/g, '"')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>');

  // Remove any remaining HTML tags (greedy regex to catch <b>, <span>, etc.)
  result = result.replace(/<[^>]*>?/gm, '');

  return result.trim();
}
