import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import {
  AssignmentNotFoundError,
  PermissionNotFoundError,
  RoleNotFoundError,
} from "../lib/errors.generated";
import { basePermission, baseRole, baseRolePermission } from "../testing/fixtures";
import { run } from "./revokePermissionFromRole";

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

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

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

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

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

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

  it("deletes RolePermission", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select
      .mockReturnValueOnce(baseRole)
      .mockReturnValueOnce(basePermission)
      .mockReturnValueOnce(baseRolePermission);
    spies.delete.mockReturnValue(baseRolePermission);

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

    expect(result.ok).toBe(true);
    expect(spies.delete).toHaveBeenCalled();
  });
});
