import assert from "node:assert/strict";
import test from "node:test";
import { buildDueBuckets, buildSectionHealth, buildStatusDistribution, summaryDelta } from "@/lib/kpis/analytics";
import type { KpiSectionDTO } from "@/lib/kpis/types";

test("status distribution summarizes all row statuses", () => {
  const rows = [
    { status: "on_track" },
    { status: "on_track" },
    { status: "watch" },
    { status: "risk" },
    { status: "no_score" },
  ] as Array<{ status: "on_track" | "watch" | "risk" | "no_score" }>;

  const distribution = buildStatusDistribution(rows as never);
  assert.deepEqual(
    distribution.map((item) => [item.status, item.value]),
    [
      ["on_track", 2],
      ["watch", 1],
      ["risk", 1],
      ["no_score", 1],
    ]
  );
});

test("due buckets classify overdue, near-term, later, and no due date", () => {
  const rows = [
    { dueDate: "2026-03-10" },
    { dueDate: "2026-03-18" },
    { dueDate: "2026-03-25" },
    { dueDate: "2026-04-20" },
    { dueDate: null },
  ] as Array<{ dueDate: string | null }>;

  const buckets = buildDueBuckets(rows as never, "2026-03-16");
  assert.deepEqual(
    buckets.map((item) => [item.key, item.value]),
    [
      ["overdue", 1],
      ["due_7d", 1],
      ["due_14d", 1],
      ["later", 1],
      ["no_due", 1],
    ]
  );
});

test("section health computes risk and score for quick scan cards", () => {
  const sections: KpiSectionDTO[] = [
    {
      id: "s1",
      sectionKey: "marketing-auto",
      rawSectionLabel: "Marketing",
      mappedDepartment: "marketing",
      ownerTeamLabel: "MKT",
      sortOrder: 0,
      rows: [
        {
          id: "r1",
          rowKey: "r1",
          responsibility: "Growth",
          objectiveIndicator: null,
          quantityQuality: null,
          compliance: null,
          dueCommitment: null,
          targetValue: null,
          quantityValue: null,
          compliancePct: 80,
          dueDate: "2026-03-20",
          status: "on_track",
          sortOrder: 0,
        },
        {
          id: "r2",
          rowKey: "r2",
          responsibility: "Engagement",
          objectiveIndicator: null,
          quantityQuality: null,
          compliance: null,
          dueCommitment: null,
          targetValue: null,
          quantityValue: null,
          compliancePct: 40,
          dueDate: "2026-03-18",
          status: "risk",
          sortOrder: 1,
        },
      ],
    },
  ];

  const result = buildSectionHealth(sections, "2026-03-16");
  assert.equal(result[0].riskRows, 1);
  assert.equal(result[0].dueSoonRows, 2);
  assert.equal(result[0].worstCompliancePct, 40);
  assert.ok(result[0].healthScore < 80);
});

test("summaryDelta returns null when previous is absent", () => {
  assert.equal(summaryDelta(25, undefined), null);
  assert.equal(summaryDelta(25, 10), 15);
});
