/**
 * Security validation utilities for user inputs and external resources
 */

/**
 * Validates if a URL is safe to fetch (SSRF prevention)
 * Blocks internal IPs, localhost, and non-HTTP(S) protocols
 */
export function isValidImageUrl(urlString: string): boolean {
  try {
    const url = new URL(urlString)

    // Only allow HTTP(S) protocols
    if (!['http:', 'https:'].includes(url.protocol)) {
      return false
    }

    // Block localhost
    if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {
      return false
    }

    // Block internal IP ranges (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
    const ip = url.hostname
    if (/^10\./.test(ip)) return false
    if (/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(ip)) return false
    if (/^192\.168\./.test(ip)) return false

    // Block link-local addresses
    if (/^169\.254\./.test(ip)) return false

    return true
  } catch {
    return false
  }
}

/**
 * Sanitizes user prompts to prevent injection attacks
 * Removes quotes, limits length, normalizes whitespace
 */
export function sanitizePrompt(input: string): string {
  if (typeof input !== 'string') {
    throw new Error('Prompt must be a string')
  }

  return input
    .trim()
    .slice(0, 500) // Limit length
    .replace(/["'`]/g, '') // Remove quotes
    .replace(/\n\n+/g, '\n') // Normalize multiple newlines
    .replace(/\r/g, '') // Remove carriage returns
}

/**
 * Validates request body size to prevent memory exhaustion
 */
export function validateContentLength(request: Request, maxSizeMB: number = 10): void {
  const contentLength = request.headers.get('content-length')
  const maxBytes = maxSizeMB * 1024 * 1024

  if (contentLength && parseInt(contentLength) > maxBytes) {
    throw new Error(`Request body too large. Maximum size: ${maxSizeMB}MB`)
  }
}

/**
 * Validates that content type is an image
 */
export function validateImageContentType(contentType: string | null): boolean {
  if (!contentType) return false
  return contentType.startsWith('image/')
}
