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 { executeTool } from "../router/assistant-tools.js";
import {
  createToolContext,
  resetEstimateToolMocks,
} from "./assistant-tools-estimate-test-helpers.js";

describe("assistant estimate version list tools", () => {
  beforeEach(() => {
    resetEstimateToolMocks();
  });

  it("lists estimate versions through the real estimate router and rejects plain users", async () => {
    const db = {
      estimate: {
        findUnique: vi.fn().mockResolvedValue({
          id: "est_1",
          name: "North Cluster Estimate",
          status: "DRAFT",
          latestVersionNumber: 4,
          versions: [
            {
              id: "ver_4",
              versionNumber: 4,
              label: "Rev 4",
              status: "IN_REVIEW",
              notes: "Latest",
              lockedAt: null,
              createdAt: new Date("2026-03-28T00:00:00.000Z"),
              updatedAt: new Date("2026-03-29T00:00:00.000Z"),
              _count: {
                assumptions: 2,
                scopeItems: 3,
                demandLines: 4,
                resourceSnapshots: 1,
                exports: 0,
              },
            },
          ],
        }),
      },
    };
    const controllerCtx = createToolContext(db, { userRole: SystemRole.CONTROLLER });
    const userCtx = createToolContext({}, { userRole: SystemRole.USER });

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

    expect(db.estimate.findUnique).toHaveBeenCalledWith({
      where: { id: "est_1" },
      select: expect.objectContaining({
        id: true,
        versions: expect.any(Object),
      }),
    });
    expect(JSON.parse(successResult.content)).toEqual(
      expect.objectContaining({
        id: "est_1",
        latestVersionNumber: 4,
        versions: [
          expect.objectContaining({
            id: "ver_4",
            versionNumber: 4,
          }),
        ],
      }),
    );
    expect(JSON.parse(deniedResult.content)).toEqual(
      expect.objectContaining({
        error: "You do not have permission to perform this action.",
      }),
    );
  });
});
