import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { RoleNotFoundError } from "../lib/errors.generated";
import { activeUser, baseRole } from "../testing/fixtures";
import { run } from "./listUserRolesByRole";

describe("listUserRolesByRole", () => {
  it("returns all users assigned to role", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseRole).mockReturnValueOnce([activeUser]);

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

  it("returns empty array when role has no user assignments", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseRole).mockReturnValueOnce([]);

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

  it("returns error when roleId does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { roleId: "nonexistent-role" });
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(RoleNotFoundError);
    }
  });

  it("returns multiple users when role has multiple user assignments", async () => {
    const { db, spies } = createMockDb<DB>();
    const secondUser = {
      ...activeUser,
      id: "user-active-2",
      email: "active2@example.com",
      name: "Active User 2",
    };
    spies.select.mockReturnValueOnce(baseRole).mockReturnValueOnce([activeUser, secondUser]);

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