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

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    approveEstimateVersion: vi.fn(),
    cloneEstimate: vi.fn(),
    commitDispoImportBatch: vi.fn(),
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    createEstimateExport: vi.fn(),
    createEstimatePlanningHandoff: vi.fn(),
    createEstimateRevision: vi.fn(),
    assessDispoImportReadiness: vi.fn(),
    loadResourceDailyAvailabilityContexts: vi.fn().mockResolvedValue(new Map()),
    getDashboardDemand: vi.fn().mockResolvedValue([]),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardOverview: vi.fn(),
    getDashboardSkillGapSummary: vi.fn().mockResolvedValue({
      roleGaps: [],
      totalOpenPositions: 0,
      skillSupplyTop10: [],
      resourcesByRole: [],
    }),
    getDashboardProjectHealth: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    getDashboardTopValueResources: vi.fn().mockResolvedValue([]),
    getEstimateById: vi.fn(),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
    stageDispoImportBatch: vi.fn(),
    submitEstimateVersion: vi.fn(),
    updateEstimateDraft: vi.fn(),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-planning-read-test-helpers.js";

describe("assistant planning skill read tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("routes skill searches through the resource router path", async () => {
    const db = {
      resource: {
        findMany: vi.fn().mockResolvedValue([
          {
            id: "res_1",
            eid: "EMP-001",
            displayName: "Bruce Banner",
            chapter: "Delivery",
            skills: [{ skill: "Houdini FX", proficiency: 4, category: "FX" }],
          },
          {
            id: "res_2",
            eid: "EMP-002",
            displayName: "Tony Stark",
            chapter: "Tech",
            skills: [{ skill: "Nuke", proficiency: 5, category: "Comp" }],
          },
        ]),
      },
    };
    const ctx = createToolContext(db, { userRole: SystemRole.CONTROLLER });

    const result = await executeTool(
      "search_by_skill",
      JSON.stringify({ skill: "houdini" }),
      ctx,
    );

    expect(db.resource.findMany).toHaveBeenCalledWith({
      where: { isActive: true },
      select: {
        id: true,
        eid: true,
        displayName: true,
        chapter: true,
        skills: true,
      },
    });
    expect(JSON.parse(result.content)).toEqual([
      {
        id: "res_1",
        eid: "EMP-001",
        name: "Bruce Banner",
        matchedSkill: "Houdini FX",
        level: 4,
        chapter: "Delivery",
      },
    ]);
  });
});
