/**
 * SVG sanitization utilities
 * Prevents XSS attacks from user-provided SVG content
 *
 * Note: Uses basic regex-based sanitization for Cloudflare Workers compatibility
 * DOMPurify doesn't work in Workers due to lack of DOM APIs
 */

/**
 * SVG sanitization - removes dangerous tags and attributes
 * Suitable for Cloudflare Workers environment
 */
export const sanitizeSvg = (svg: string): string => {
  if (!svg || typeof svg !== 'string') {
    return ''
  }

  let sanitized = svg

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

  // Remove dangerous tags and their content
  sanitized = sanitized.replace(/<(iframe|object|embed|style|link|meta|base)[^>]*>.*?<\/\1>/gi, '')
  sanitized = sanitized.replace(/<(iframe|object|embed|style|link|meta|base)[^>]*\/?>/gi, '')

  // Remove event handlers (onclick, onload, onerror, etc.)
  sanitized = sanitized.replace(/\s+on\w+\s*=\s*["'][^"']*["']/gi, '')
  sanitized = sanitized.replace(/\s+on\w+\s*=\s*[^\s>]+/gi, '')

  // Remove javascript: URLs
  sanitized = sanitized.replace(/javascript\s*:/gi, '')

  // Remove data: URLs (except for images which are safe in SVGs)
  sanitized = sanitized.replace(/(?<!image\/)data\s*:/gi, '')

  // Remove style attributes that could contain expressions
  sanitized = sanitized.replace(/\s+style\s*=\s*["'][^"']*expression[^"']*["']/gi, '')

  return sanitized
}
