import { beforeEach, describe, expect, it, vi } from "vitest";
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, type ToolContext } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-vacation-entitlement-test-helpers.js";

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

  it("returns a stable assistant error when vacation approval 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(
      "approve_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 approval violates lifecycle preconditions", async () => {
    const ctx = createToolContext(
      {
        vacation: {
          findUnique: vi.fn().mockResolvedValue({
            id: "vac_approved",
            resource: { displayName: "Alice Example" },
          }),
        },
      },
      { userRole: SystemRole.MANAGER },
    );

    const result = await executeTool(
      "approve_vacation",
      JSON.stringify({ vacationId: "vac_approved" }),
      {
        ...ctx,
        db: {
          ...ctx.db,
          vacation: {
            ...((ctx.db as Record<string, unknown>).vacation as Record<string, unknown>),
            findUnique: vi.fn()
              .mockResolvedValueOnce({
                id: "vac_approved",
                resource: { displayName: "Alice Example" },
              })
              .mockResolvedValueOnce({
                id: "vac_approved",
                resource: { displayName: "Alice Example" },
              }),
            update: vi.fn().mockRejectedValue(
              new TRPCError({
                code: "BAD_REQUEST",
                message: "Only PENDING, CANCELLED, or REJECTED vacations can be approved",
              }),
            ),
          },
        } as ToolContext["db"],
      },
    );

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