/**
 * Minimal CSV serializer — no external dependencies.
 * Converts an array of flat objects to RFC 4180-compliant CSV text.
 */

function escapeCell(value: unknown): string {
  if (value === null || value === undefined) return "";
  const str = String(value);
  // Quote if contains comma, quote, newline, or leading/trailing whitespace
  if (/[",\n\r]/.test(str) || str !== str.trim()) {
    return `"${str.replace(/"/g, '""')}"`;
  }
  return str;
}

export function toCSV(rows: Record<string, unknown>[]): string {
  if (rows.length === 0) return "";
  const headers = Object.keys(rows[0]);
  const lines = [
    headers.join(","),
    ...rows.map(row => headers.map(h => escapeCell(row[h])).join(",")),
  ];
  return lines.join("\r\n");
}

/**
 * Send a CSV response with proper headers.
 */
import type { Response } from "express";
export function sendCSV(res: Response, rows: Record<string, unknown>[], filename: string): void {
  const csv = toCSV(rows);
  res.setHeader("Content-Type", "text/csv; charset=utf-8");
  res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
  res.send("﻿" + csv); // BOM for Excel UTF-8 compatibility
}
