// src/lib/admin/csv.ts — tiny, dependency-free RFC-4180 CSV serializer.
//
// Used by the God-Mode structured-export route handlers. We never inject a CSV
// dependency: a robust serializer is ~20 lines. Each row is a flat record of
// already-primitive values (dates pre-stringified to ISO, nested objects
// pre-stringified to JSON by the caller) keyed by the same `columns`.

/** Format a single cell as a string. null/undefined → "" (empty field). */
function cell(value: unknown): string {
  if (value === null || value === undefined) return "";
  if (value instanceof Date) return value.toISOString();
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}

/**
 * RFC-4180 field escaping: a field is wrapped in double-quotes when it contains
 * a comma, a double-quote or a CR/LF; internal double-quotes are doubled.
 */
function escapeField(raw: string): string {
  if (/[",\r\n]/.test(raw)) {
    return `"${raw.replace(/"/g, '""')}"`;
  }
  return raw;
}

/**
 * Serialize `rows` to a CSV string: a header row (the column keys) followed by
 * one line per row, fields in `columns` order, CRLF line endings.
 */
export function toCsv(
  columns: readonly string[],
  rows: ReadonlyArray<Record<string, unknown>>,
): string {
  const header = columns.map(escapeField).join(",");
  const body = rows.map((row) =>
    columns.map((col) => escapeField(cell(row[col]))).join(","),
  );
  return [header, ...body].join("\r\n");
}
