/**
 * Minimal RFC 4180 CSV serialization + browser-side download helper.
 *
 * The serializer handles the four awkward cases that show up in real data:
 *   - commas inside a field (quote it)
 *   - quotes inside a field (double them, then quote it)
 *   - newlines inside a field (quote it)
 *   - null / undefined / empty values (render as empty cell)
 *
 * Anything that isn't a primitive is coerced via String(); numeric inputs are
 * emitted verbatim (no locale formatting — the caller is responsible for
 * `toFixed(2)` and friends).
 *
 * `downloadCsv` is intentionally synchronous: the browser serializes the blob
 * in the same tick and we revoke the object URL on the next microtask so the
 * download dialog still gets a live URL. No setTimeout needed.
 */

export type CsvColumn<T> = {
  /** Display label written to the header row. */
  header: string;
  /** Cell extractor. Return primitives only. */
  value: (row: T) => string | number | null | undefined;
};

const NEEDS_QUOTING = /[",\r\n]/;

function escapeField(raw: string | number | null | undefined): string {
  if (raw === null || raw === undefined) return "";
  const s = typeof raw === "string" ? raw : String(raw);
  if (NEEDS_QUOTING.test(s)) {
    return `"${s.replace(/"/g, '""')}"`;
  }
  return s;
}

/**
 * Serialize an array of rows to an RFC 4180 CSV string.
 *
 * Lines are joined with `\r\n` per the spec. The output ends with a trailing
 * CRLF so the last row is terminated identically to the rest — Excel and
 * Numbers both prefer this for auto-detecting row count.
 */
export function toCsv<T>(
  rows: T[],
  columns: CsvColumn<T>[],
): string {
  const header = columns.map((c) => escapeField(c.header)).join(",");
  if (rows.length === 0) {
    // No body rows: emit header + CRLF only. The two CRLFs that would
    // appear from "empty body + terminator" are dropped — a trailing blank
    // line confuses Excel's row-count heuristics.
    return `${header}\r\n`;
  }
  const body = rows
    .map((row) => columns.map((c) => escapeField(c.value(row))).join(","))
    .join("\r\n");
  // RFC 4180: every record (including the header) is CRLF-terminated.
  // A row that serializes to "" still produces a CRLF in body plus the
  // terminator CRLF, yielding two CRLFs after the header.
  return `${header}\r\n${body}\r\n`;
}

/**
 * Default filename for a CSV download: `{prefix}-{YYYY-MM-DD}.csv` using the
 * local date. We slice an ISO string instead of constructing the date with
 * `getFullYear` etc. because the ISO format matches the rest of the codebase.
 */
export function defaultCsvFilename(prefix: string, now: Date = new Date()): string {
  const isoDay = now.toISOString().slice(0, 10);
  return `${prefix}-${isoDay}.csv`;
}

/**
 * Trigger a browser download of `csvText` as a file. Creates an in-memory
 * Blob, attaches it to a hidden `<a download>`, clicks the link, then revokes
 * the object URL on the next tick so the download still has a live handle.
 *
 * Safe to call from SSR/Node — guards against a missing `document`.
 */
export function downloadCsv(filename: string, csvText: string): void {
  if (typeof document === "undefined" || typeof URL === "undefined") return;
  // Prepend BOM so Excel auto-detects UTF-8 on Windows. Tools that already
  // understand UTF-8 (Numbers, Google Sheets, every CSV parser in this repo)
  // ignore the leading bytes silently.
  const blob = new Blob(["\ufeff", csvText], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  // Some browsers require the link to be in the DOM before .click() works.
  a.style.display = "none";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  // Defer revoke so the browser has the URL handle when the download kicks off.
  queueMicrotask(() => URL.revokeObjectURL(url));
}