import { beforeEach, describe, expect, it, vi } from "vitest";
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(),
    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 weekly phasing read errors", () => {
  beforeEach(() => {
    resetEstimateToolMocks();
  });

  it("returns a stable error when get_estimate_weekly_phasing cannot find the estimate", async () => {
    vi.mocked(getEstimateById).mockResolvedValueOnce(null as never);

    const ctx = createToolContext({}, {
      userRole: SystemRole.CONTROLLER,
    });
    const result = await executeTool(
      "get_estimate_weekly_phasing",
      JSON.stringify({ estimateId: "est_missing" }),
      ctx,
    );

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

  it("returns a stable error when get_estimate_weekly_phasing cannot find a working version", async () => {
    vi.mocked(getEstimateById).mockResolvedValueOnce({
      id: "est_empty",
      name: "Estimate Empty",
      versions: [],
    } as Awaited<ReturnType<typeof getEstimateById>>);

    const ctx = createToolContext({}, {
      userRole: SystemRole.CONTROLLER,
    });
    const result = await executeTool(
      "get_estimate_weekly_phasing",
      JSON.stringify({ estimateId: "est_empty" }),
      ctx,
    );

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