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 read tools", () => {
  beforeEach(() => {
    resetEstimateToolMocks();
  });

  it("returns stable read errors for missing estimates and versions", async () => {
    vi.mocked(getEstimateById).mockResolvedValueOnce(null as never);

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

    const detailResult = await executeTool(
      "get_estimate_detail",
      JSON.stringify({ estimateId: "missing_estimate" }),
      detailCtx,
    );

    expect(JSON.parse(detailResult.content)).toEqual({
      error: "Estimate not found with the given criteria.",
    });

    const versionsCtx = createToolContext(
      {
        estimate: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      { userRole: SystemRole.CONTROLLER },
    );

    const versionsResult = await executeTool(
      "list_estimate_versions",
      JSON.stringify({ estimateId: "missing_estimate" }),
      versionsCtx,
    );

    expect(JSON.parse(versionsResult.content)).toEqual({
      error: "Estimate not found with the given criteria.",
    });

    const snapshotCtx = createToolContext(
      {
        estimate: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      {
        userRole: SystemRole.CONTROLLER,
        permissions: [PermissionKey.VIEW_COSTS],
      },
    );

    const snapshotResult = await executeTool(
      "get_estimate_version_snapshot",
      JSON.stringify({ estimateId: "missing_estimate", versionId: "missing_version" }),
      snapshotCtx,
    );

    expect(JSON.parse(snapshotResult.content)).toEqual({
      error: "Estimate version not found with the given criteria.",
    });
  });
});
