import DOMPurify from 'dompurify'

/**
 * XSS 消毒:清理用户输入的 HTML,防止 XSS 攻击
 * 用于所有 v-html 渲染和富文本场景
 */
export function sanitizeHtml(dirty: string): string {
  return DOMPurify.sanitize(dirty, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br', 'ul', 'ol', 'li', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'code', 'pre', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td'],
    ALLOWED_ATTR: ['href', 'target', 'rel', 'src', 'alt', 'class', 'style'],
    ALLOW_DATA_ATTR: false,
  })
}

/**
 * 纯文本转义:防止用户输入在非 v-html 场景中被注入
 */
export function escapeHtml(str: string): string {
  const map: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;',
  }
  return str.replace(/[&<>"']/g, (m) => map[m])
}

/**
 * URL 安全校验:防止 javascript: 协议注入
 */
export function sanitizeUrl(url: string): string {
  const trimmed = url.trim().toLowerCase()
  if (trimmed.startsWith('javascript:') || trimmed.startsWith('data:text/html')) {
    return '#'
  }
  return url
}

/**
 * CSP 安全违规报告上报
 */
export function reportCSPViolation(report: SecurityPolicyViolationEvent): void {
  console.warn('[CSP 违规]', {
    documentURI: report.documentURI,
    blockedURI: report.blockedURI,
    violatedDirective: report.violatedDirective,
    disposition: report.disposition,
  })
  // TODO: 上报至错误监控服务 (Sentry / 自建)
}