/**
 * Minimal CSV serialiser. Quotes every cell, escapes embedded
 * quotes per RFC 4180. No streaming — fine for the export endpoints
 * which cap at a few thousand rows.
 */

export function toCsv(headers: string[], rows: Array<Array<string | number | null | undefined>>): string {
  const escape = (cell: unknown): string => {
    if (cell == null) return '""';
    const s = typeof cell === "string" ? cell : String(cell);
    return `"${s.replace(/"/g, '""')}"`;
  };
  const lines = [
    headers.map(escape).join(","),
    ...rows.map((row) => row.map(escape).join(",")),
  ];
  return lines.join("\n");
}
