/**
 * CSV cell escaping that prevents formula injection.
 *
 * A CSV cell whose first character is `=`, `+`, `-`, `@`, `\t`, or `\r` is
 * interpreted as a formula by Excel and LibreOffice when the file is opened.
 * Even with the "enable content" prompt for DDE, `=HYPERLINK(...)` and
 * `=WEBSERVICE(...)` execute on cell focus and can exfiltrate row data to an
 * attacker-controlled URL. Because user-controlled fields (project titles,
 * names, free-text feedback, User-Agent strings persisted to audit logs) end
 * up in our exports, we must defang any leading formula character.
 *
 * The defense: prefix the cell with a single quote `'` so spreadsheet apps
 * treat the value as text. Then apply standard CSV quoting (wrap in `"` and
 * double-up internal quotes) when the cell contains commas, quotes, or
 * newlines.
 */
export function csvCell(value: unknown): string {
  if (value === null || value === undefined) return ''
  let s = String(value)

  if (s.length > 0) {
    const first = s.charCodeAt(0)
    // = + - @  \t  \r
    if (
      first === 0x3d ||
      first === 0x2b ||
      first === 0x2d ||
      first === 0x40 ||
      first === 0x09 ||
      first === 0x0d
    ) {
      s = `'${s}`
    }
  }

  if (s.includes(',') || s.includes('"') || s.includes('\n')) {
    return `"${s.replace(/"/g, '""')}"`
  }
  return s
}
