import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { PermissionNotFoundError, RoleNotFoundError } from "../lib/errors.generated";
import { baseRole } 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",
      permission: "sales:salesOrder:create",
    });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleNotFoundError);
    }
  });

  it("throws when permission is not in the role's permissions array", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue({ ...baseRole, permissions: [] });

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

  it("removes permission key from role's permissions array", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const roleWithPermissions = {
      ...baseRole,
      permissions: ["sales:salesOrder:create", "inventory:stockOperation:approve"],
    };
    const updatedRole = {
      ...baseRole,
      permissions: ["inventory:stockOperation:approve"],
      updatedAt: new Date(),
    };
    spies.select.mockReturnValue(roleWithPermissions);
    spies.update.mockReturnValue(updatedRole);

    const result = await run(db, {
      roleId: baseRole.id,
      permission: "sales:salesOrder:create",
    });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.role.permissions).not.toContain("sales:salesOrder:create");
      expect(result.value.role.permissions).toContain("inventory:stockOperation:approve");
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
