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

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

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

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

    mock.enqueueResults(
      [activeUser],
      [baseRole],
      [baseUserRole],
      [baseUserRole],
      [], // Permission keys from recompute (empty after revoke)
      [updatedUser],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        userId: activeUser.id,
        roleId: baseRole.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.user.permissions).toEqual([]);
    }
    expect(mock.deletes.length).toBeGreaterThan(0);
  });
});
