import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseRole, permissions: [] }]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    const roleWithPermissions = {
      ...baseRole,
      permissions: ["sales:salesOrder:create", "inventory:stockOperation:approve"],
    };
    const updatedRole = {
      ...baseRole,
      permissions: ["inventory:stockOperation:approve"],
      updatedAt: new Date(),
    };
    mock.enqueueResults([roleWithPermissions], [updatedRole]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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(mock.updates.length).toBeGreaterThan(0);
  });
});
