import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseRole, adminRole, inactiveRole } from "../testing/fixtures";
import { run } from "./listRoles";

describe("listRoles", () => {
  it("returns all roles when no filters applied", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseRole, adminRole, inactiveRole]);

    const result = await run(mock.db, {});

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(3);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("returns roles filtered by ACTIVE status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseRole, adminRole]);

    const result = await run(mock.db, { status: "ACTIVE" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      expect(result.value.hasNextPage).toBe(false);
    }
    const query = mock.selects[0];
    expect(query.sql).toMatch(/"status"/);
    expect(query.parameters).toContain("ACTIVE");
  });

  it("returns roles filtered by INACTIVE status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveRole]);

    const result = await run(mock.db, { status: "INACTIVE" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.hasNextPage).toBe(false);
    }
    const query = mock.selects[0];
    expect(query.sql).toMatch(/"status"/);
    expect(query.parameters).toContain("INACTIVE");
  });

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

    const result = await run(mock.db, {});

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(0);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("returns empty list when no roles match the status filter", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { status: "INACTIVE" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(0);
      expect(result.value.hasNextPage).toBe(false);
    }
  });
});
