/**
 * 간이 CSV 변환 유틸 — client-side only.
 * BOM 포함하여 엑셀에서 한글 깨짐 방지.
 */

export function toCsvString(
  rows: Record<string, any>[],
  columns: { key: string; label: string; format?: (v: any, row: Record<string, any>) => string }[],
): string {
  const header = columns.map((c) => escapeCsv(c.label)).join(",");
  const body = rows
    .map((row) =>
      columns
        .map((c) => {
          const raw = c.format ? c.format(row[c.key], row) : row[c.key];
          return escapeCsv(raw);
        })
        .join(","),
    )
    .join("\n");
  return "﻿" + header + "\n" + body;
}

function escapeCsv(v: any): string {
  if (v === null || v === undefined) return "";
  const s = String(v);
  if (/[",\n\r]/.test(s)) {
    return `"${s.replace(/"/g, '""')}"`;
  }
  return s;
}

export function downloadCsv(filename: string, content: string) {
  const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
