import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } 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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activeUser).mockReturnValueOnce([baseRole]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(activeUser).mockReturnValueOnce([]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    const secondRole = {
      ...baseRole,
      id: "role-2",
      name: "Admin",
    };
    spies.select.mockReturnValueOnce(activeUser).mockReturnValueOnce([baseRole, secondRole]);

    const result = await run(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]);
    }
  });
});
