import { beforeEach, describe, expect, it, vi } from "vitest";
import { PermissionKey } from "@capakraken/shared";

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

vi.mock("../sse/event-bus.js", () => ({
  emitAllocationCreated: vi.fn(),
  emitAllocationDeleted: vi.fn(),
  emitAllocationUpdated: vi.fn(),
  emitProjectShifted: vi.fn(),
}));

vi.mock("../lib/budget-alerts.js", () => ({
  checkBudgetThresholds: vi.fn(),
}));

vi.mock("../lib/cache.js", () => ({
  invalidateDashboardCache: vi.fn(),
}));

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

describe("assistant advanced timeline holiday overlay tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns holiday overlays through the real timeline detail path", async () => {
    const ctx = createToolContext(
      {
        demandRequirement: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        assignment: {
          findMany: vi.fn().mockResolvedValue([
            {
              id: "asg_by",
              projectId: "project_1",
              resourceId: "res_by",
              startDate: new Date("2026-01-05T00:00:00.000Z"),
              endDate: new Date("2026-01-09T00:00:00.000Z"),
              hoursPerDay: 8,
              status: "CONFIRMED",
              metadata: null,
              project: {
                id: "project_1",
                name: "Gelddruckmaschine",
                shortCode: "GDM",
                orderType: "CHARGEABLE",
                clientId: "client_1",
                budgetCents: 0,
                winProbability: 100,
                status: "ACTIVE",
                startDate: new Date("2026-01-05T00:00:00.000Z"),
                endDate: new Date("2026-01-16T00:00:00.000Z"),
              },
              resource: {
                id: "res_by",
                displayName: "Bayern User",
                eid: "EMP-BY",
                chapter: "Delivery",
              },
            },
          ]),
        },
        resource: {
          findMany: vi.fn().mockResolvedValue([
            {
              id: "res_by",
              countryId: "country_de",
              federalState: "BY",
              metroCityId: null,
              country: { code: "DE" },
              metroCity: null,
            },
          ]),
        },
        project: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        holidayCalendar: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        country: {
          findUnique: vi.fn(),
        },
        metroCity: {
          findUnique: vi.fn(),
        },
      },
      [PermissionKey.USE_ASSISTANT_ADVANCED_TOOLS],
    );

    const result = await executeTool(
      "get_timeline_holiday_overlays",
      JSON.stringify({
        startDate: "2026-01-05",
        endDate: "2026-01-09",
        projectIds: ["project_1"],
      }),
      ctx,
    );

    const parsed = JSON.parse(result.content) as {
      period: { startDate: string; endDate: string };
      filters: { projectIds: string[] };
      summary: {
        overlayCount: number;
        holidayResourceCount: number;
        byScope: Array<{ scope: string; count: number }>;
      };
      overlays: Array<{ resourceId: string; startDate: string; note: string; scope: string }>;
    };

    expect(parsed.period).toEqual({
      startDate: "2026-01-05",
      endDate: "2026-01-09",
    });
    expect(parsed.filters).toEqual({ projectIds: ["project_1"] });
    expect(parsed.summary).toEqual({
      overlayCount: 1,
      holidayResourceCount: 1,
      byScope: [{ scope: "STATE", count: 1 }],
    });
    expect(parsed.overlays).toEqual([
      expect.objectContaining({
        resourceId: "res_by",
        startDate: "2026-01-06",
        note: "Heilige Drei Könige",
        scope: "STATE",
      }),
    ]);
  });
});
