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 { getEstimateById } from "@capakraken/application";

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

describe("assistant estimate detail read tools", () => {
  beforeEach(() => {
    resetEstimateToolMocks();
  });

  it("reads estimate details through the real estimate router and rejects plain users", async () => {
    vi.mocked(getEstimateById).mockResolvedValue({
      id: "est_1",
      name: "North Cluster Estimate",
      status: "DRAFT",
      versions: [],
    } as Awaited<ReturnType<typeof getEstimateById>>);

    const controllerCtx = createToolContext(
      {},
      {
        userRole: SystemRole.CONTROLLER,
        permissions: [PermissionKey.VIEW_COSTS],
      },
    );
    const userCtx = createToolContext({}, { userRole: SystemRole.USER });

    const successResult = await executeTool(
      "get_estimate_detail",
      JSON.stringify({ estimateId: "est_1" }),
      controllerCtx,
    );
    const deniedResult = await executeTool(
      "get_estimate_detail",
      JSON.stringify({ estimateId: "est_1" }),
      userCtx,
    );

    expect(vi.mocked(getEstimateById)).toHaveBeenCalledWith(controllerCtx.db, "est_1");
    expect(JSON.parse(successResult.content)).toEqual(
      expect.objectContaining({
        id: "est_1",
        name: "North Cluster Estimate",
      }),
    );
    expect(JSON.parse(deniedResult.content)).toEqual(
      expect.objectContaining({
        error: "You do not have permission to perform this action.",
      }),
    );
  });
});
