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 clients read tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(countPlanningEntries).mockResolvedValue({ countsByRoleId: new Map() });
  });

  it("routes client reads through their backing router", async () => {
    const db = {
      client: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "client_1",
            name: "Acme Mobility",
            code: "ACM",
            parentId: null,
            isActive: true,
            sortOrder: 1,
            tags: [],
            createdAt: new Date("2026-01-01T00:00:00.000Z"),
            updatedAt: new Date("2026-01-02T00:00:00.000Z"),
            _count: { children: 0, projects: 4 },
          },
        ]),
      },
    };
    const ctx = createToolContext(db, {
      userRole: SystemRole.CONTROLLER,
      permissions: [PermissionKey.VIEW_PLANNING],
    });

    const clientsResult = await executeTool(
      "list_clients",
      JSON.stringify({ query: "ACM", limit: 5 }),
      ctx,
    );

    expect(db.client.findMany).toHaveBeenCalledWith({
      where: {
        isActive: true,
        OR: [
          { name: { contains: "ACM", mode: "insensitive" } },
          { code: { contains: "ACM", mode: "insensitive" } },
        ],
      },
      include: { _count: { select: { children: true, projects: true } } },
      orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
    });
    expect(JSON.parse(clientsResult.content)).toEqual([
      {
        id: "client_1",
        name: "Acme Mobility",
        code: "ACM",
        projectCount: 4,
      },
    ]);
  });
});
