import { beforeEach, describe, expect, it, vi } from "vitest";
import { countPlanningEntries } from "@capakraken/application";
import { 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 { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-master-data-read-test-helpers.js";

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

  it("routes calculation rule reads through their backing router", async () => {
    const db = {
      calculationRule: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "calc_1",
            name: "Rush Fee",
            description: "Adds cost for rush work",
            isActive: true,
            triggerType: "RUSH",
            orderType: null,
            costEffect: "INCREASE",
            costReductionPercent: null,
            chargeabilityEffect: "NONE",
            priority: 90,
            project: { id: "proj_1", name: "Falcon", shortCode: "FAL" },
          },
        ]),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.CONTROLLER });

    const calculationRulesResult = await executeTool("list_calculation_rules", "{}", ctx);

    expect(db.calculationRule.findMany).toHaveBeenCalledWith({
      orderBy: [{ priority: "desc" }, { name: "asc" }],
      include: {
        project: {
          select: {
            id: true,
            shortCode: true,
            name: true,
            status: true,
            endDate: true,
          },
        },
      },
    });

    expect(JSON.parse(calculationRulesResult.content)).toEqual([
      expect.objectContaining({
        id: "calc_1",
        name: "Rush Fee",
        project: expect.objectContaining({
          id: "proj_1",
          shortCode: "FAL",
        }),
      }),
    ]);
  });
});
