/**
 * Multi-sheet 總表 export for the 採購 chart page — mirrors on-screen charts and drill-down data.
 */
import { exportMultiSheetToXlsx, type MultiSheetSpec } from "../_components/exportChartToXlsx";

export type PurchaseChartMasterExportPayload = {
  /** ISO timestamp for audit */
  exportedAtIso: string;
  /** 篩選與情境 — key-value rows */
  metaRows: Record<string, unknown>[];
  /** 預計送貨 donut (依預計到貨日、上方篩選) */
  estimatedDonutRows: Record<string, unknown>[];
  /** 實際已送貨 donut (依訂單日期、上方篩選) */
  actualStatusDonutRows: Record<string, unknown>[];
  /** 貨品摘要表 (當前 drill) */
  itemSummaryRows: Record<string, unknown>[];
  /** 供應商分佈 (由採購單明細彙總) */
  supplierDistributionRows: Record<string, unknown>[];
  /** 採購單列表 */
  purchaseOrderListRows: Record<string, unknown>[];
  /** 全量採購單行明細 (每張 PO 所有行) */
  purchaseOrderLineRows: Record<string, unknown>[];
};

function sheetOrPlaceholder(name: string, rows: Record<string, unknown>[], emptyMessage: string): MultiSheetSpec {
  if (rows.length > 0) return { name, rows };
  return {
    name,
    rows: [{ 說明: emptyMessage }],
  };
}

/**
 * Build worksheet specs (used by {@link exportPurchaseChartMasterToFile}).
 */
export function buildPurchaseChartMasterSheets(payload: PurchaseChartMasterExportPayload): MultiSheetSpec[] {
  return [
    { name: "篩選條件與情境", rows: payload.metaRows },
    sheetOrPlaceholder("預計送貨", payload.estimatedDonutRows, "無資料（請確認訂單日期與篩選）"),
    sheetOrPlaceholder("實際已送貨", payload.actualStatusDonutRows, "無資料"),
    sheetOrPlaceholder("貨品摘要", payload.itemSummaryRows, "無資料（可能為篩選交集為空或未載入）"),
    sheetOrPlaceholder("供應商分佈", payload.supplierDistributionRows, "無資料"),
    sheetOrPlaceholder("採購單列表", payload.purchaseOrderListRows, "無採購單明細可匯出"),
    sheetOrPlaceholder("採購單行明細", payload.purchaseOrderLineRows, "無行資料（採購單列表為空）"),
  ];
}

export function exportPurchaseChartMasterToFile(
  payload: PurchaseChartMasterExportPayload,
  filenameBase: string
): void {
  const sheets = buildPurchaseChartMasterSheets(payload);
  exportMultiSheetToXlsx(sheets, filenameBase);
}
