/**
 * Security constants shared across rehype plugins
 */
import type { Element } from 'hast'

// Maximum allowed length for code blocks (50KB)
export const MAX_CODE_LENGTH = 50000

// Maximum size for uploaded images (cover + content)
export const MAX_IMAGE_BYTES = 2_000_000
export const MAX_IMAGE_LABEL = '2 MB'

// Dangerous patterns to check in Mermaid diagrams
export const DANGEROUS_MERMAID_PATTERNS = [
  /<script>/i,           // Prevent script tags
  /javascript:/i,        // Prevent javascript: URLs
  /onerror=/i,          // Prevent onerror handlers
  /onclick=/i,          // Prevent onclick handlers
  /onload=/i,           // Prevent onload handlers
  /onmouseover=/i,      // Prevent mouseover handlers
  /data:.*script/i,     // Prevent data: URLs with scripts
  /xlink:href/i,        // Prevent xlink:href abuse
  /<\s*(?:embed|object|iframe)/i, // Prevent embedded content
]

// Helper function to validate Mermaid syntax
export const validateMermaidSyntax = (code: string): boolean => {
  // Return false if any dangerous pattern is found
  return !DANGEROUS_MERMAID_PATTERNS.some(pattern => pattern.test(code))
}

// Helper function to create error elements
export const createErrorElement = (message: string, className: string): Element => ({
  type: 'element',
  tagName: 'div',
  properties: {
    className: [className, 'p-4', 'border', 'border-red-300', 'rounded-lg', 'bg-red-50', 'text-red-700', 'my-6']
  },
  children: [
    {
      type: 'element',
      tagName: 'p',
      properties: {
        className: ['font-semibold']
      },
      children: [
        {
          type: 'text',
          value: 'Error'
        }
      ]
    },
    {
      type: 'element',
      tagName: 'p',
      properties: {
        className: ['text-sm', 'mt-1']
      },
      children: [
        {
          type: 'text',
          value: message
        }
      ]
    }
  ]
})