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

  it("returns a stable assistant error when vacation creation receives an invalid end date", 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),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "create_vacation",
      JSON.stringify({
        resourceId: "EMP-001",
        type: "ANNUAL",
        startDate: "2026-09-07",
        endDate: "2026-09-99",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Invalid endDate: 2026-09-99",
    });
  });

  it("returns a stable assistant error when vacation creation overlaps an existing request", 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),
        },
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1", systemRole: "MANAGER" }),
        },
        vacation: {
          findFirst: vi.fn().mockResolvedValue({
            id: "vac_existing",
            resourceId: "res_1",
          }),
        },
      },
      { userRole: SystemRole.MANAGER },
    );

    const result = await executeTool(
      "create_vacation",
      JSON.stringify({
        resourceId: "EMP-001",
        type: "ANNUAL",
        startDate: "2026-09-07",
        endDate: "2026-09-09",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Overlapping vacation already exists for this resource in the selected period",
    });
  });

  it("returns a stable assistant error when a user tries to create vacation for another resource", async () => {
    const ctx = createToolContext(
      {
        resource: {
          findUnique: vi.fn()
            .mockResolvedValueOnce(null)
            .mockResolvedValueOnce({
              id: "res_1",
              eid: "EMP-001",
              displayName: "Alice Example",
              chapter: "Delivery",
              isActive: true,
            })
            .mockResolvedValueOnce({
              userId: "user_2",
            }),
          findFirst: vi.fn().mockResolvedValue({
            id: "res_1",
          }),
        },
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1", systemRole: "USER" }),
        },
      },
      { userRole: SystemRole.USER },
    );

    const result = await executeTool(
      "create_vacation",
      JSON.stringify({
        resourceId: "EMP-001",
        type: "ANNUAL",
        startDate: "2026-09-07",
        endDate: "2026-09-09",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "You can only create vacation requests for your own resource.",
    });
  });
});
