/**
 * Basic server-side string sanitization for Convex mutations.
 * Strips HTML tags, trims whitespace, and enforces max length.
 * Does NOT use DOMPurify (not available in Convex runtime).
 */
export function sanitizeString(input: string, maxLength = 10000): string {
  return input
    .replace(/<[^>]*>/g, "") // Strip HTML tags
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&amp;/g, "&") // Decode common entities then re-strip
    .replace(/<[^>]*>/g, "") // Second pass after entity decode
    .trim()
    .slice(0, maxLength);
}

export function sanitizeOptionalString(
  input: string | undefined,
  maxLength = 10000,
): string | undefined {
  if (!input) return input;
  return sanitizeString(input, maxLength);
}
