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

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

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

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    const secondUser = {
      ...activeUser,
      id: "user-active-2",
      email: "active2@example.com",
      name: "Active User 2",
    };
    mock.enqueueResults([baseRole], [activeUser, secondUser]);

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