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 delete tool - success", () => {
  beforeEach(() => {
    resetRoleMutationMocks();
  });

  it("routes deletion through the backing router and returns the expected assistant payload", async () => {
    const roleRecord = createRoleRecord();
    const db = {
      role: {
        findUnique: vi.fn()
          .mockResolvedValueOnce(roleRecord)
          .mockResolvedValueOnce(roleRecord)
          .mockResolvedValueOnce({
            id: "role_1",
            name: "Senior CG Artist",
            description: "Pipeline lead",
            color: "#222222",
            isActive: true,
            _count: { resourceRoles: 0 },
          }),
        delete: vi.fn().mockResolvedValue({ id: "role_1" }),
      },
      auditLog: {
        create: vi.fn().mockResolvedValue({ id: "audit_1" }),
      },
      demandRequirement: {
        groupBy: vi.fn().mockResolvedValue([]),
      },
      assignment: {
        groupBy: vi.fn().mockResolvedValue([]),
      },
    };
    const ctx = createToolContext(db, {
      userRole: SystemRole.ADMIN,
      permissions: [PermissionKey.MANAGE_ROLES],
    });

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

    expect(JSON.parse(deleteRoleResult.content)).toEqual(expect.objectContaining({
      success: true,
      message: "Deleted role: Senior CG Artist",
    }));
    expect(db.role.delete).toHaveBeenCalledWith({ where: { id: "role_1" } });
    expect(db.auditLog.create).toHaveBeenCalled();
  });
});
