import { beforeEach, describe, expect, it, vi } from "vitest";
import { PermissionKey, SystemRole } from "@capakraken/shared";

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

import { countPlanningEntries } from "@capakraken/application";
import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-master-data-read-test-helpers.js";

describe("assistant master data org units read tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(countPlanningEntries).mockResolvedValue({ countsByRoleId: new Map() });
  });

  it("routes org unit reads through their backing router", async () => {
    const db = {
      orgUnit: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "ou_delivery",
            name: "Delivery",
            shortName: "DEL",
            level: 5,
            parentId: null,
            sortOrder: 1,
            isActive: true,
            createdAt: new Date("2026-01-01T00:00:00.000Z"),
            updatedAt: new Date("2026-01-02T00:00:00.000Z"),
          },
        ]),
        findUnique: vi.fn().mockResolvedValue({
          id: "ou_delivery",
          name: "Delivery",
          shortName: "DEL",
          level: 5,
          parentId: null,
          sortOrder: 1,
          isActive: true,
          createdAt: new Date("2026-01-01T00:00:00.000Z"),
          updatedAt: new Date("2026-01-02T00:00:00.000Z"),
          parent: null,
          children: [],
          _count: { resources: 7 },
        }),
      },
    };
    const ctx = createToolContext(db, {
      userRole: SystemRole.CONTROLLER,
      permissions: [PermissionKey.VIEW_ALL_RESOURCES],
    });

    const orgUnitsResult = await executeTool(
      "list_org_units",
      JSON.stringify({ level: 5 }),
      ctx,
    );

    expect(db.orgUnit.findMany).toHaveBeenCalledWith({
      where: {
        level: 5,
        isActive: true,
      },
      orderBy: [{ level: "asc" }, { sortOrder: "asc" }, { name: "asc" }],
    });
    expect(db.orgUnit.findUnique).toHaveBeenCalledWith({
      where: { id: "ou_delivery" },
      include: {
        parent: true,
        children: { orderBy: { sortOrder: "asc" } },
        _count: { select: { resources: true } },
      },
    });

    expect(JSON.parse(orgUnitsResult.content)).toEqual([
      {
        id: "ou_delivery",
        name: "Delivery",
        shortName: "DEL",
        level: 5,
        parent: null,
        resourceCount: 7,
      },
    ]);
  });
});
