// 엑셀 다운로드 헬퍼 (xlsx)
import * as XLSX from "xlsx";

export interface XlsxColumn<T> {
  header: string;
  key: keyof T | ((row: T) => string | number);
  width?: number;
}

export function downloadXlsx<T>(
  filename: string,
  rows: T[],
  columns: XlsxColumn<T>[],
  sheetName = "Sheet1"
): void {
  const data = rows.map((r) => {
    const o: Record<string, string | number> = {};
    for (const c of columns) {
      const v = typeof c.key === "function"
        ? c.key(r)
        : ((r as Record<string, unknown>)[c.key as string] as string | number);
      o[c.header] = v ?? "";
    }
    return o;
  });
  const ws = XLSX.utils.json_to_sheet(data);
  if (columns.some((c) => c.width)) {
    ws["!cols"] = columns.map((c) => ({ wch: c.width ?? 14 }));
  }
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, sheetName);
  const stamp = new Date().toISOString().replace(/[-:]/g, "").slice(0, 13);
  XLSX.writeFile(wb, `${filename}_${stamp}.xlsx`);
}
