import { beforeEach, describe, expect, it, vi } from "vitest";
import { VacationStatus } from "@capakraken/db";
import { SystemRole } from "@capakraken/shared";
import { TRPCError } from "@trpc/server";

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    approveEstimateVersion: vi.fn(),
    cloneEstimate: vi.fn(),
    commitDispoImportBatch: vi.fn(),
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    createEstimateExport: vi.fn(),
    createEstimatePlanningHandoff: vi.fn(),
    createEstimateRevision: vi.fn(),
    assessDispoImportReadiness: vi.fn(),
    loadResourceDailyAvailabilityContexts: vi.fn().mockResolvedValue(new Map()),
    getDashboardDemand: vi.fn().mockResolvedValue([]),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardOverview: vi.fn(),
    getDashboardSkillGapSummary: vi.fn().mockResolvedValue({
      roleGaps: [],
      totalOpenPositions: 0,
      skillSupplyTop10: [],
      resourcesByRole: [],
    }),
    getDashboardProjectHealth: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    getDashboardTopValueResources: vi.fn().mockResolvedValue([]),
    getEstimateById: vi.fn(),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
    stageDispoImportBatch: vi.fn(),
    submitEstimateVersion: vi.fn(),
    updateEstimateDraft: vi.fn(),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-vacation-entitlement-test-helpers.js";

describe("assistant vacation cancellation error paths", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable assistant error when vacation cancellation cannot resolve the request", async () => {
    const ctx = createToolContext(
      {
        vacation: {
          findUnique: vi.fn().mockRejectedValue(
            new TRPCError({ code: "NOT_FOUND", message: "Vacation not found" }),
          ),
        },
      },
      { userRole: SystemRole.MANAGER },
    );

    const result = await executeTool(
      "cancel_vacation",
      JSON.stringify({ vacationId: "vac_missing" }),
      ctx,
    );

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

  it("returns a stable assistant error when vacation cancellation violates lifecycle preconditions", async () => {
    const alreadyCancelledVacation = {
      id: "vac_cancelled",
      status: VacationStatus.CANCELLED,
      requestedById: "user_1",
      resource: { displayName: "Alice Example", userId: "user_1" },
    };
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1", systemRole: "USER" }),
        },
        vacation: {
          findUnique: vi.fn().mockResolvedValue(alreadyCancelledVacation),
        },
      },
      { userRole: SystemRole.USER, permissions: [] },
    );

    const result = await executeTool(
      "cancel_vacation",
      JSON.stringify({ vacationId: "vac_cancelled" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Vacation cannot be cancelled in its current status.",
    });
  });
});
