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 { todayForFilename, type ExportTable } from "@/lib/export-file";

import type { DashboardCards } from "./service/cdc-gpsf-dashboard-service";

// Builders for the tables inside exported files. Each takes the SAME data
// the charts render, so the files always match what is on screen.

// buildExportFilename("agencies", "csv")
//   -> "working-group-dashboard-agencies-2026-07-09.csv"
export function buildExportFilename(base: string, extension: string): string {
  return `working-group-dashboard-${base}-${todayForFilename()}.${extension}`;
}

// The five numbers from the summary cards row.
export function buildSummaryTable(cards: DashboardCards): ExportTable {
  return {
    title: "Summary",
    headers: ["Metric", "Count"],
    rows: [
      ["Total Issues", cards.totalIssues],
      ["Solved", cards.solved],
      ["In Progress", cards.inProgress],
      ["Not Addressed", cards.notAddressed],
      ["Total Primary Agencies", cards.totalPrimaryAgencies],
    ],
  };
}

// Matches the donut chart and its legend. Always lists all three statuses,
// zeros included, even when the chart hides an empty slice.
export function buildStatusTable(cards: DashboardCards): ExportTable {
  return {
    title: "Status",
    headers: ["Status", "Count"],
    rows: [
      ["Solved", cards.solved],
      ["In Progress", cards.inProgress],
      ["Not Addressed", cards.notAddressed],
      ["Total", cards.totalIssues],
    ],
  };
}

// Matches the agencies bar chart (Solved / In Progress / Not Addressed).
export function buildAgenciesTable(rows: AgencyStatusRow[]): ExportTable {
  return {
    title: "Agencies",
    headers: ["Agency", "Solved", "In Progress", "Not Addressed", "Total"],
    rows: rows.map((row) => {
      const notAddressed = row.notAddressed ?? 0;
      return [
        row.name,
        row.solved,
        row.inProgress,
        notAddressed,
        row.solved + row.inProgress + notAddressed,
      ];
    }),
  };
}

// Matches the working group stacked bars.
export function buildWorkingGroupsTable(
  rows: WorkingGroupStatusRow[],
): ExportTable {
  return {
    title: "Working Groups",
    headers: ["Working Group", "Solved", "In Progress", "Not Addressed", "Total"],
    rows: rows.map((row) => [
      row.label,
      row.solved,
      row.inProgress,
      row.notAddressed,
      row.solved + row.inProgress + row.notAddressed,
    ]),
  };
}

// Matches the category bar chart.
export function buildCategoriesTable(rows: CategoryIssueRow[]): ExportTable {
  return {
    title: "Categories",
    headers: ["Category", "Issues"],
    rows: rows.map((row) => [row.label, row.value]),
  };
}
