import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import {
  AssignmentNotFoundError,
  RoleNotFoundError,
  UserNotFoundError,
} from "../lib/errors.generated";
import { activeUser, baseRole, baseUserRole } from "../testing/fixtures";
import { run } from "./revokeRoleFromUser";

describe("revokeRoleFromUser", () => {
  it("throws when user does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, {
      userId: "nonexistent-user",
      roleId: baseRole.id,
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UserNotFoundError);
    }
  });

  it("throws when role does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeUser).mockReturnValueOnce(undefined);

    const result = await run(db, {
      userId: activeUser.id,
      roleId: "nonexistent-role",
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleNotFoundError);
    }
  });

  it("throws when assignment does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(activeUser)
      .mockReturnValueOnce(baseRole)
      .mockReturnValueOnce(undefined);

    const result = await run(db, {
      userId: activeUser.id,
      roleId: baseRole.id,
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AssignmentNotFoundError);
    }
  });

  it("deletes UserRole and recomputes permissions", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedUser = { ...activeUser, permissions: [] };

    spies.select
      .mockReturnValueOnce(activeUser)
      .mockReturnValueOnce(baseRole)
      .mockReturnValueOnce(baseUserRole)
      .mockReturnValueOnce([]); // Permission keys from recompute (empty after revoke)
    spies.delete.mockReturnValue(baseUserRole);
    spies.update.mockReturnValue(updatedUser);

    const result = await run(db, {
      userId: activeUser.id,
      roleId: baseRole.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.user.permissions).toEqual([]);
    }
    expect(spies.delete).toHaveBeenCalled();
  });
});
