import { beforeEach, describe, expect, it, vi } from "vitest";

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-test-helpers.js";

describe("assistant holiday calendar mutation tools - success", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("creates a holiday calendar through the assistant for admin users", async () => {
    const ctx = createToolContext({
      country: {
        findUnique: vi.fn().mockResolvedValue({ id: "country_de", code: "DE", name: "Deutschland" }),
      },
      holidayCalendar: {
        findFirst: vi.fn().mockResolvedValue(null),
        create: vi.fn().mockResolvedValue({
          id: "cal_by",
          name: "Bayern Feiertage",
          scopeType: "STATE",
          stateCode: "BY",
          isActive: true,
          priority: 10,
          country: { id: "country_de", code: "DE", name: "Deutschland" },
          metroCity: null,
          entries: [],
        }),
      },
    });

    const result = await executeTool(
      "create_holiday_calendar",
      JSON.stringify({
        name: "Bayern Feiertage",
        scopeType: "STATE",
        countryId: "country_de",
        stateCode: "BY",
        priority: 10,
      }),
      ctx,
    );

    const parsed = JSON.parse(result.content) as {
      success: boolean;
      message: string;
      calendar: { name: string; stateCode: string | null };
    };

    expect(parsed.success).toBe(true);
    expect(parsed.message).toContain("Created holiday calendar");
    expect(parsed.calendar).toEqual(
      expect.objectContaining({
        name: "Bayern Feiertage",
        stateCode: "BY",
      }),
    );
  });

  it("updates and deletes holiday calendars for admin users", async () => {
    const holidayCalendarCreate = vi.fn().mockResolvedValue({
      id: "cal_de",
      name: "Germany National",
      scopeType: "COUNTRY",
      stateCode: null,
      isActive: true,
      priority: 0,
      country: { id: "country_de", code: "DE", name: "Germany" },
      metroCity: null,
      entries: [],
    });
    const holidayCalendarUpdate = vi.fn().mockResolvedValue({
      id: "cal_de",
      name: "Germany National Updated",
      scopeType: "COUNTRY",
      stateCode: null,
      isActive: false,
      priority: 1,
      country: { id: "country_de", code: "DE", name: "Germany" },
      metroCity: null,
      entries: [],
    });
    const holidayCalendarDelete = vi.fn().mockResolvedValue({ id: "cal_de" });
    const ctx = createToolContext({
      country: {
        findUnique: vi.fn().mockResolvedValue({ id: "country_de", code: "DE", name: "Germany" }),
      },
      holidayCalendar: {
        findFirst: vi.fn().mockResolvedValue(null),
        findUnique: vi.fn()
          .mockResolvedValueOnce({
            id: "cal_de",
            name: "Germany National",
            scopeType: "COUNTRY",
            countryId: "country_de",
          })
          .mockResolvedValueOnce({
            id: "cal_de",
            name: "Germany National Updated",
            scopeType: "COUNTRY",
            countryId: "country_de",
          }),
        create: holidayCalendarCreate,
        update: holidayCalendarUpdate,
        delete: holidayCalendarDelete,
      },
    });

    const createCalendarResult = await executeTool(
      "create_holiday_calendar",
      JSON.stringify({ name: "Germany National", scopeType: "COUNTRY", countryId: "country_de" }),
      ctx,
    );
    const updateCalendarResult = await executeTool(
      "update_holiday_calendar",
      JSON.stringify({ id: "cal_de", data: { name: "Germany National Updated", isActive: false, priority: 1 } }),
      ctx,
    );
    const deleteCalendarResult = await executeTool(
      "delete_holiday_calendar",
      JSON.stringify({ id: "cal_de" }),
      ctx,
    );

    expect(holidayCalendarCreate).toHaveBeenCalledWith({
      data: {
        name: "Germany National",
        scopeType: "COUNTRY",
        countryId: "country_de",
        isActive: true,
        priority: 0,
      },
      include: {
        country: { select: { id: true, code: true, name: true } },
        metroCity: { select: { id: true, name: true } },
        entries: { orderBy: [{ date: "asc" }, { name: "asc" }] },
      },
    });
    expect(holidayCalendarUpdate).toHaveBeenCalledWith({
      where: { id: "cal_de" },
      data: {
        name: "Germany National Updated",
        isActive: false,
        priority: 1,
      },
      include: {
        country: { select: { id: true, code: true, name: true } },
        metroCity: { select: { id: true, name: true } },
        entries: { orderBy: [{ date: "asc" }, { name: "asc" }] },
      },
    });
    expect(holidayCalendarDelete).toHaveBeenCalledWith({ where: { id: "cal_de" } });
    expect(JSON.parse(createCalendarResult.content)).toEqual(
      expect.objectContaining({ success: true, message: "Created holiday calendar: Germany National" }),
    );
    expect(JSON.parse(updateCalendarResult.content)).toEqual(
      expect.objectContaining({ success: true, message: "Updated holiday calendar: Germany National Updated" }),
    );
    expect(JSON.parse(deleteCalendarResult.content)).toEqual(
      expect.objectContaining({ success: true, message: "Deleted holiday calendar: Germany National Updated" }),
    );
  });
});
