/**
 * A small, dependency-free CSV serializer (RFC 4180-ish). Used for client-side "export the currently loaded
 * page" affordances (e.g. the partner settlement invoices table) — no server round-trip, no library.
 */

export interface CsvColumn {
  /** The row-object key this column reads. */
  key: string;
  /** Already-translated column header. */
  label: string;
}

/** Wraps a field in double quotes (doubling any internal quote) when it contains a comma, quote, or newline. */
function quoteField(value: string): string {
  if (/[",\r\n]/.test(value)) {
    return `"${value.replace(/"/g, '""')}"`;
  }
  return value;
}

/**
 * Builds a CSV string (header row + one row per item, `\r\n` line endings — Excel expects CRLF) from a list
 * of plain row objects and a column spec. Values are stringified as-is (callers pre-format money/dates);
 * any field containing a comma, double quote, or newline is quoted per RFC 4180.
 */
export function toCsv(rows: Record<string, string | number>[], headers: CsvColumn[]): string {
  const lines = [
    headers.map((h) => quoteField(h.label)).join(','),
    ...rows.map((row) => headers.map((h) => quoteField(String(row[h.key] ?? ''))).join(',')),
  ];
  return lines.join('\r\n');
}
