import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { UserNotFoundError } from "../lib/errors.generated";
import { activeUser, baseRole } from "../testing/fixtures";
import { run } from "./listUserRolesByUser";

describe("listUserRolesByUser", () => {
  it("returns all roles assigned to user", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeUser], [baseRole]);

    const result = await run(mock.db, { userId: activeUser.id });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.roles).toEqual([baseRole]);
    }
  });

  it("returns empty array when user has no roles", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeUser], []);

    const result = await run(mock.db, { userId: activeUser.id });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.roles).toEqual([]);
    }
  });

  it("returns error when userId does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

  it("returns multiple roles when user has multiple role assignments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const secondRole = {
      ...baseRole,
      id: "role-2",
      name: "Admin",
    };
    mock.enqueueResults([activeUser], [baseRole, secondRole]);

    const result = await run(mock.db, { userId: activeUser.id });
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.roles).toHaveLength(2);
      expect(result.value.roles).toEqual([baseRole, secondRole]);
    }
  });
});
