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(),
    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 entitlement error paths", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable assistant error when the entitlement resource disappears before saving", async () => {
    const ctx = createToolContext(
      {
        resource: {
          findUnique: vi.fn()
            .mockResolvedValueOnce(null)
            .mockResolvedValueOnce({
              id: "res_1",
              eid: "EMP-001",
              displayName: "Alice Example",
              chapter: "Delivery",
            }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        vacationEntitlement: {
          findUnique: vi.fn().mockResolvedValue(null),
          create: vi.fn().mockRejectedValue({
            code: "P2003",
            message: "Foreign key constraint failed",
            meta: { field_name: "VacationEntitlement_resourceId_fkey" },
          }),
        },
      },
      { userRole: SystemRole.MANAGER },
    );

    const result = await executeTool(
      "set_entitlement",
      JSON.stringify({ resourceId: "EMP-001", year: 2027, entitledDays: 32 }),
      ctx,
    );

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

  it("returns a stable assistant error when entitlement carryover is passed manually", async () => {
    const ctx = createToolContext(
      {
        resource: {
          findUnique: vi.fn(),
          findFirst: vi.fn(),
        },
      },
      { userRole: SystemRole.MANAGER },
    );

    const result = await executeTool(
      "set_entitlement",
      JSON.stringify({
        resourceId: "EMP-001",
        year: 2027,
        entitledDays: 32,
        carryoverDays: 3,
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Manual carryoverDays is not supported here. Carryover is computed automatically from prior-year balances.",
    });
    expect(ctx.db.resource.findUnique).not.toHaveBeenCalled();
    expect(ctx.db.resource.findFirst).not.toHaveBeenCalled();
  });
});
