import { beforeEach, describe, expect, it, vi } from "vitest";
import { StagedRecordStatus } from "@capakraken/db";
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-dispo-test-helpers.js";

describe("assistant dispo staged resource and project listing tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("forwards staged dispo resource queries through the real dispo router path", async () => {
    const ctx = createToolContext(
      {
        stagedResource: {
          findMany: vi.fn().mockResolvedValue([
            {
              id: "sr_1",
              importBatchId: "batch_1",
              canonicalExternalId: "EMP-001",
              status: "PARSED",
            },
          ]),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "list_dispo_staged_resources",
      JSON.stringify({ importBatchId: "batch_1", status: "PARSED", limit: 10 }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      items: [
        expect.objectContaining({
          id: "sr_1",
          importBatchId: "batch_1",
          canonicalExternalId: "EMP-001",
          status: "PARSED",
        }),
      ],
    });
  });

  it("lists staged dispo projects through the real router path", async () => {
    const findMany = vi.fn().mockResolvedValue([
      {
        id: "sp_2",
        importBatchId: "batch_1",
        projectKey: "BETA",
        status: StagedRecordStatus.PARSED,
        isTbd: true,
      },
      {
        id: "sp_1",
        importBatchId: "batch_1",
        projectKey: "OMEGA",
        status: StagedRecordStatus.PARSED,
        isTbd: true,
      },
    ]);
    const ctx = createToolContext(
      {
        stagedProject: {
          findMany,
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "list_dispo_staged_projects",
      JSON.stringify({
        importBatchId: "batch_1",
        status: StagedRecordStatus.PARSED,
        isTbd: true,
        limit: 1,
      }),
      ctx,
    );

    expect(findMany).toHaveBeenCalledWith({
      where: {
        importBatchId: "batch_1",
        status: StagedRecordStatus.PARSED,
        isTbd: true,
      },
      orderBy: { projectKey: "asc" },
      take: 2,
    });
    expect(JSON.parse(result.content)).toEqual({
      items: [
        expect.objectContaining({
          id: "sp_2",
          projectKey: "BETA",
          isTbd: true,
        }),
      ],
      nextCursor: "sp_1",
    });
  });
});
