// Shared CSV helpers used by admin export endpoints. Centralizing the
// escape logic keeps the formula-injection mitigation consistent across
// the audit-log export, the role-permission-history export, and any
// future CSV download we add.
export function csvEscape(value: unknown): string {
  if (value === null || value === undefined) return "";
  let s = typeof value === "string" ? value : String(value);
  // Mitigate CSV/spreadsheet formula injection (Excel, LibreOffice, Google
  // Sheets evaluate cells starting with =, +, -, @, or a tab/CR as formulas).
  // Prefix a single quote so the spreadsheet renders the value as text.
  if (s.length > 0 && /^[=+\-@\t\r]/.test(s)) {
    s = `'${s}`;
  }
  if (/[",\r\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
  return s;
}
