import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseUnitKg, baseUnitGram, baseUnitPound } from "../testing/fixtures";
import { run } from "./listUnitsByCategory";

describe("listUnitsByCategory", () => {
  it("returns paginated units with default page size", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseUnitKg, baseUnitGram]);

    const result = await run(db, { categoryId: "category-1" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseUnitKg, baseUnitGram]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("returns hasNextPage true when more results exist", async () => {
    const { db, spies } = createMockDb<DB>();
    // Simulate limit+1 rows returned (3 rows for limit=2)
    spies.select.mockReturnValue([baseUnitKg, baseUnitGram, baseUnitPound]);

    const result = await run(db, { categoryId: "category-1", limit: 2 });

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

  it("returns empty result when no units match", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, { categoryId: "nonexistent" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("respects custom limit and offset", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseUnitGram]);

    const result = await run(db, {
      categoryId: "category-1",
      limit: 1,
      offset: 1,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseUnitGram]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("accepts orderBy and orderDirection", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseUnitGram, baseUnitKg]);

    const result = await run(db, {
      categoryId: "category-1",
      orderBy: "name",
      orderDirection: "desc",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseUnitGram, baseUnitKg]);
    }
  });
});
