import { beforeEach, describe, expect, it, vi } from "vitest";
import {
  DispoStagedRecordType,
  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 record resolution tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("resolves staged dispo records through the real router path", async () => {
    const update = vi.fn().mockResolvedValue({
      id: "sa_1",
      status: StagedRecordStatus.APPROVED,
    });
    const ctx = createToolContext(
      {
        stagedAssignment: {
          update,
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "resolve_dispo_staged_record",
      JSON.stringify({
        id: "sa_1",
        recordType: DispoStagedRecordType.ASSIGNMENT,
        action: "APPROVE",
      }),
      ctx,
    );

    expect(update).toHaveBeenCalledWith({
      where: { id: "sa_1" },
      data: { status: StagedRecordStatus.APPROVED },
    });
    expect(JSON.parse(result.content)).toEqual({
      id: "sa_1",
      status: StagedRecordStatus.APPROVED,
    });
  });
});
