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

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

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

  it("creates a country for admin users and returns an invalidation action", async () => {
    const ctx = createToolContext({
      country: {
        findUnique: vi.fn().mockResolvedValue(null),
        create: vi.fn().mockResolvedValue({
          id: "country_es",
          code: "ES",
          name: "Spain",
          dailyWorkingHours: 8,
          scheduleRules: null,
          isActive: true,
          metroCities: [],
          _count: { resources: 0 },
        }),
      },
    });

    const result = await executeTool(
      "create_country",
      JSON.stringify({ code: "ES", name: "Spain", dailyWorkingHours: 8 }),
      ctx,
    );

    expect(result.action).toEqual({
      type: "invalidate",
      scope: ["country", "resource", "holidayCalendar", "vacation"],
    });
    expect(result.data).toMatchObject({
      success: true,
      country: { code: "ES", name: "Spain" },
    });
  });

  it("updates a country for admin users and keeps invalidation semantics stable", async () => {
    const update = vi.fn().mockResolvedValue({
      id: "country_es",
      code: "ES",
      name: "Spain Updated",
      dailyWorkingHours: 7.5,
      scheduleRules: { shortFriday: true },
      isActive: false,
      metroCities: [],
      _count: { resources: 0 },
    });
    const ctx = createToolContext({
      country: {
        findUnique: vi.fn().mockResolvedValue({ id: "country_es", code: "ES", name: "Spain" }),
        update,
      },
    });

    const result = await executeTool(
      "update_country",
      JSON.stringify({
        id: "country_es",
        data: {
          name: "Spain Updated",
          dailyWorkingHours: 7.5,
          scheduleRules: null,
          isActive: false,
        },
      }),
      ctx,
    );

    expect(update).toHaveBeenCalledWith({
      where: { id: "country_es" },
      data: {
        name: "Spain Updated",
        dailyWorkingHours: 7.5,
        scheduleRules: expect.anything(),
        isActive: false,
      },
      include: { metroCities: true },
    });
    expect(result.action).toEqual({
      type: "invalidate",
      scope: ["country", "resource", "holidayCalendar", "vacation"],
    });
    expect(result.data).toMatchObject({
      success: true,
      country: { id: "country_es", isActive: false, name: "Spain Updated" },
    });
  });
});
