// A CSV the merchant opens in a spreadsheet. A cell that starts with = + - or @ would be read as a formula by the
// spreadsheet (a lot named "=HYPERLINK(...)"), so it is prefixed with an apostrophe.
const FORMULA_START = /^[=+\-@\t\r]/;

export function csvCell(value: string | number | null): string {
  if (value === null) return "";
  let text = String(value);
  if (typeof value === "string" && FORMULA_START.test(text)) text = `'${text}`;
  return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}

export function toCsv(header: string[], rows: Array<Array<string | number | null>>): string {
  return [header, ...rows].map((row) => row.map(csvCell).join(",")).join("\r\n") + "\r\n";
}

// Money as a plain decimal ("12.50"), what a spreadsheet reads as a number.
export const decimal = (cents: number): string => (cents / 100).toFixed(2);
