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

import {
  createRoleRecord,
  createToolContext,
  executeTool,
  resetRoleMutationMocks,
} from "./assistant-tools-role-mutation-test-helpers.js";

describe("assistant role mutation tools", () => {
  beforeEach(() => {
    resetRoleMutationMocks();
  });

  it("returns a stable error when creating a duplicate role", async () => {
    const ctx = createToolContext(
      {
        role: {
          findUnique: vi.fn().mockResolvedValue({ id: "role_existing", name: "CG Artist" }),
        },
      },
      {
        userRole: SystemRole.MANAGER,
        permissions: [PermissionKey.MANAGE_ROLES],
      },
    );

    const result = await executeTool(
      "create_role",
      JSON.stringify({ name: "CG Artist" }),
      ctx,
    );

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

  it("returns a stable error when updating a missing role", async () => {
    const ctx = createToolContext(
      {
        role: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      {
        userRole: SystemRole.MANAGER,
        permissions: [PermissionKey.MANAGE_ROLES],
      },
    );

    const result = await executeTool(
      "update_role",
      JSON.stringify({ id: "role_missing", name: "Senior CG Artist" }),
      ctx,
    );

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

  it("returns a stable error when deleting an assigned role", async () => {
    const roleRecord = createRoleRecord({ _count: { resourceRoles: 1 } });
    const ctx = createToolContext(
      {
        role: {
          findUnique: vi.fn()
            .mockResolvedValueOnce(roleRecord)
            .mockResolvedValueOnce(roleRecord),
        },
        demandRequirement: {
          groupBy: vi.fn().mockResolvedValue([]),
        },
        assignment: {
          groupBy: vi.fn().mockResolvedValue([]),
        },
      },
      {
        userRole: SystemRole.MANAGER,
        permissions: [PermissionKey.MANAGE_ROLES],
      },
    );

    const result = await executeTool(
      "delete_role",
      JSON.stringify({ id: "role_1" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(expect.objectContaining({
      error: "Role cannot be deleted while it is still assigned. Deactivate it instead.",
    }));
  });
});
