/**
 * Security & Input Sanitization Utilities
 * Prevents Cross-Site Scripting (XSS), SQL/NoSQL Injection, and Email Header Injection.
 */

/**
 * Sanitizes plain text input by stripping dangerous tags, script blocks, null bytes, and malicious HTML
 */
export function sanitizeText(input: unknown): string {
  if (typeof input !== "string") return "";
  
  return input
    // Remove null bytes
    .replace(/\0/g, "")
    // Remove script tags and content
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
    // Remove dangerous HTML tags
    .replace(/<[\/\s]*(?:applet|embed|object|frameset|frame|iframe|meta|link|style)[^>]*>/gi, "")
    // Remove event handlers like onload, onclick, onerror
    .replace(/on\w+\s*=\s*["'][^"']*["']/gi, "")
    // Strip standalone tags but preserve alphanumeric content
    .replace(/<[^>]+>/g, "")
    .trim();
}

/**
 * Sanitizes and validates an email address.
 * Strips Carriage Return (\r) and Line Feed (\n) characters to prevent Email Header Injection (CRLF).
 */
export function sanitizeEmail(email: unknown): string | null {
  if (typeof email !== "string") return null;

  // Strip CRLF injection vectors
  const clean = email.replace(/[\r\n\t]/g, "").trim().toLowerCase();

  // RFC-compliant safe email regex
  const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;

  if (!emailRegex.test(clean) || clean.length > 254) {
    return null;
  }

  return clean;
}

/**
 * Sanitizes phone numbers, keeping only international prefix (+), digits, hyphens, and spaces.
 */
export function sanitizePhone(phone: unknown): string {
  if (typeof phone !== "string") return "";
  // Keep only +, numbers, space, hyphens, parentheses
  return phone.replace(/[^\d+()\s-]/g, "").trim().slice(0, 30);
}
