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,
    approveEstimateVersion: vi.fn(),
    cloneEstimate: vi.fn(),
    createEstimateExport: vi.fn(),
    createEstimatePlanningHandoff: vi.fn(),
    createEstimateRevision: vi.fn(),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    getEstimateById: vi.fn(),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
    submitEstimateVersion: vi.fn(),
    updateEstimateDraft: vi.fn(),
  };
});

import { cloneEstimate } from "@capakraken/application";

import { executeTool } from "../router/assistant-tools.js";
import {
  createToolContext,
  resetEstimateToolMocks,
} from "./assistant-tools-estimate-test-helpers.js";

describe("assistant estimate clone errors", () => {
  beforeEach(() => {
    resetEstimateToolMocks();
  });

  it("returns stable assistant errors for clone_estimate mutations", async () => {
    const cases = [
      {
        payload: { sourceEstimateId: "est_missing" },
        setup: () => vi.mocked(cloneEstimate).mockRejectedValueOnce(new Error("Source estimate not found")),
        expected: "Estimate not found with the given criteria.",
      },
      {
        payload: { sourceEstimateId: "est_empty" },
        setup: () => vi.mocked(cloneEstimate).mockRejectedValueOnce(new Error("Source estimate has no versions")),
        expected: "Source estimate has no versions and cannot be cloned.",
      },
    ] as const;

    for (const testCase of cases) {
      testCase.setup();
      const ctx = createToolContext({}, {
        userRole: SystemRole.MANAGER,
        permissions: [PermissionKey.MANAGE_PROJECTS],
      });

      const result = await executeTool(
        "clone_estimate",
        JSON.stringify(testCase.payload),
        ctx,
      );

      expect(JSON.parse(result.content)).toEqual({ error: testCase.expected });
    }
  });
});
