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([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

vi.mock("../lib/audit.js", () => ({
  createAuditEntry: vi.fn().mockResolvedValue(undefined),
}));

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

describe("assistant resource availability tool", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("checks resource availability with regional holidays excluded from capacity", async () => {
    const resourceRecord = {
      id: "res_1",
      displayName: "Bruce Banner",
      eid: "bruce.banner",
      fte: 1,
      availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8, saturday: 0, sunday: 0 },
      countryId: "country_de",
      federalState: "BY",
      metroCityId: null,
      country: { code: "DE", dailyWorkingHours: 8 },
      metroCity: null,
    };
    const db = {
      resource: {
        findUnique: vi.fn().mockResolvedValue(resourceRecord),
        findFirst: vi.fn(),
      },
      assignment: {
        findMany: vi.fn().mockResolvedValue([
          {
            hoursPerDay: 8,
            startDate: new Date("2026-01-05T00:00:00.000Z"),
            endDate: new Date("2026-01-06T00:00:00.000Z"),
            status: "CONFIRMED",
            project: { name: "Gamma", shortCode: "GAM" },
          },
        ]),
      },
      vacation: {
        findMany: vi.fn().mockResolvedValue([]),
      },
    };
    const ctx = createToolContext(db, [PermissionKey.VIEW_PLANNING]);

    const result = await executeTool(
      "check_resource_availability",
      JSON.stringify({ resourceId: "res_1", startDate: "2026-01-05", endDate: "2026-01-06" }),
      ctx,
    );

    const parsed = JSON.parse(result.content) as {
      workingDays: number;
      periodAvailableHours: number;
      periodBookedHours: number;
      periodRemainingHours: number;
      availableHoursPerDay: number;
      isFullyAvailable: boolean;
    };

    expect(parsed.workingDays).toBe(1);
    expect(parsed.periodAvailableHours).toBe(8);
    expect(parsed.periodBookedHours).toBe(8);
    expect(parsed.periodRemainingHours).toBe(0);
    expect(parsed.availableHoursPerDay).toBe(0);
    expect(parsed.isFullyAvailable).toBe(false);
  });
});
