import assert from "node:assert/strict";
import test from "node:test";
import { canEditWeeklyKpiRow, canViewWeeklyKpiBoard, scopeSectionsForViewer } from "@/lib/kpis/persistence";
import { prisma } from "@/lib/prisma";

test.after(async () => {
  await prisma.$disconnect();
});

test("canViewWeeklyKpiBoard authorizes owner and leader variants", () => {
  assert.equal(canViewWeeklyKpiBoard({ role: "owner", department: null }), true);
  assert.equal(canViewWeeklyKpiBoard({ role: "leader", department: "marketing" }), true);
  assert.equal(canViewWeeklyKpiBoard({ role: "lead", department: "marketing" }), true);
  assert.equal(canViewWeeklyKpiBoard({ role: "employee", department: "marketing" }), false);
});

test("canEditWeeklyKpiRow allows owner and same-department leaders to update KPI rows", () => {
  assert.equal(canEditWeeklyKpiRow({ role: "owner", department: null }, "marketing"), true);
  assert.equal(canEditWeeklyKpiRow({ role: "leader", department: "marketing" }, "marketing"), true);
  assert.equal(canEditWeeklyKpiRow({ role: "leader", department: "operaciones" }, "marketing"), false);
  assert.equal(canEditWeeklyKpiRow({ role: "leader", department: "administracion" }, "capital_humano"), true);
  assert.equal(canEditWeeklyKpiRow({ role: "lead", department: "marketing" }, "marketing"), true);
  assert.equal(canEditWeeklyKpiRow({ role: "leader", department: "marketing" }, null), false);
  assert.equal(canEditWeeklyKpiRow({ role: "employee", department: "marketing" }, "marketing"), false);
});

test("scopeSectionsForViewer keeps leader data scoped", () => {
  const sections = [
    { mappedDepartment: "marketing" as const, id: "s1" },
    { mappedDepartment: "operaciones" as const, id: "s2" },
    { mappedDepartment: "capital_humano" as const, id: "s3" },
  ];

  const ownerView = scopeSectionsForViewer(sections, { role: "owner", department: null });
  assert.equal(ownerView.length, 3);

  const leaderView = scopeSectionsForViewer(sections, { role: "leader", department: "operaciones" });
  assert.deepEqual(leaderView.map((section) => section.id), ["s2"]);

  const adminLeaderView = scopeSectionsForViewer(sections, { role: "leader", department: "administracion" });
  assert.deepEqual(adminLeaderView.map((section) => section.id), ["s3"]);

  const leadAliasView = scopeSectionsForViewer(sections, { role: "lead", department: "marketing" });
  assert.deepEqual(leadAliasView.map((section) => section.id), ["s1"]);
});
