/** Shared input-sanitization helpers for API routes — trims, strips control characters, and escapes HTML before it ever reaches an email template. */

const CONTROL_CHARS = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;

/** Trims whitespace and strips all control characters, including newlines (which could otherwise be used for header injection). Safe for single-line fields. */
export function sanitizeLine(value: string): string {
  return value.replace(/[\r\n]+/g, " ").replace(CONTROL_CHARS, "").trim();
}

/** Trims and strips control characters but preserves single newlines, for multi-line fields like a message body. */
export function sanitizeText(value: string): string {
  return value
    .replace(/\r\n/g, "\n")
    .replace(CONTROL_CHARS, "")
    .trim();
}

/** Escapes HTML-significant characters so untrusted strings can't inject markup into an HTML email template. */
export function escapeHtml(value: string): string {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}
