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

    const result = await run(mock.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);
    }
    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("category-1");
    expect(mock.selects[0].sql).toMatch(/"categoryId"/);
  });

  it("returns hasNextPage true when more results exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // Simulate limit+1 rows returned (3 rows for limit=2)
    mock.enqueueResults([baseUnitKg, baseUnitGram, baseUnitPound]);

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

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

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseUnitGram, baseUnitKg]);
    }
    expect(mock.selects[0].sql).toMatch(/order by .*"name" desc/i);
  });
});
