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

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

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

  it("returns a stable error when creating a country with a duplicate code", async () => {
    const ctx = createToolContext({
      country: {
        findUnique: vi.fn().mockResolvedValue({
          id: "country_es_existing",
          code: "ES",
          name: "Existing Spain",
        }),
      },
    });

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

    expect(JSON.parse(result.content)).toEqual({
      error: "A country with this code already exists.",
    });
  });

  it("returns a stable error when updating a missing country", async () => {
    const ctx = createToolContext({
      country: {
        findUnique: vi.fn().mockResolvedValue(null),
      },
    });

    const result = await executeTool(
      "update_country",
      JSON.stringify({ id: "country_missing", data: { name: "Atlantis" } }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Country not found with the given criteria.",
    });
  });

  it("refuses country mutations for non-admin users", async () => {
    const ctx = createToolContext({ country: {} }, [], SystemRole.MANAGER);

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

    expect(JSON.parse(result.content)).toEqual({
      error: "You do not have permission to perform this action.",
    });
  });
});
