// Builds the files the Export buttons download. Every table is built from
// the SAME rows the charts render, so a file always matches the screen.
//
// The page has one Export button per card plus one for the whole page, so
// the tables are grouped the same way the cards are.

import type { AgencyStatusRow } from "@/features/ministry/dashboard/components/charts/agency-status-card";
import type { CategoryIssueRow } from "@/features/ministry/dashboard/components/charts/category-issues-card";
import type { WorkingGroupStatusRow } from "@/features/ministry/dashboard/components/charts/dashboard-status-card";
import {
  buildAgenciesTable,
  buildCategoriesTable,
  buildStatusTable,
  buildSummaryTable,
  buildWorkingGroupsTable,
} from "@/features/cdc-gpsf/dashboard/cdc-gpsf-dashboard-export";
import { todayForFilename, type ExportTable } from "@/lib/export-file";

import type {
  DraftDashboardCards,
  DraftDashboardStage,
} from "./draft-dashboard-service";

// buildDraftDashboardFilename("csv")                        -> "pswg-draft-dashboard-2026-08-13.csv"
// buildDraftDashboardFilename("png", "agencies")            -> "pswg-draft-dashboard-agencies-2026-08-13.png"
// buildDraftDashboardFilename("csv", undefined, "final")    -> "pswg-final-dashboard-2026-08-13.csv"
export function buildDraftDashboardFilename(
  extension: string,
  part?: string,
  stage: DraftDashboardStage = "draft",
): string {
  const middle = part ? `${part}-` : "";
  return `pswg-${stage}-dashboard-${middle}${todayForFilename()}.${extension}`;
}

export type DraftDashboardExportInput = {
  cards: DraftDashboardCards;
  agencyRows: AgencyStatusRow[];
  workingGroupRows: WorkingGroupStatusRow[];
  categoryRows: CategoryIssueRow[];
};

// One entry per Export button on the page. `all` is the page-level button:
// every table, one worksheet each.
export function buildDraftDashboardExportParts(
  input: DraftDashboardExportInput,
) {
  const summary = buildSummaryTable(input.cards);
  const status = buildStatusTable(input.cards);
  const agencies = buildAgenciesTable(input.agencyRows);
  const workingGroups = buildWorkingGroupsTable(input.workingGroupRows);
  const categories = buildCategoriesTable(input.categoryRows);

  return {
    all: [summary, status, agencies, workingGroups, categories],
    // The donut card shows the status split, with the total in the middle.
    overall: [status],
    agencies: [agencies],
    workingGroups: [workingGroups],
    categories: [categories],
  } satisfies Record<string, ExportTable[]>;
}
