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

describe("getUoMCategory", () => {
  describe("by id", () => {
    it("returns category when found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([baseUoMCategory]);

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.uoMCategory).toEqual(baseUoMCategory);
      }
      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0].parameters).toContain("category-1");
      expect(mock.selects[0].sql).toMatch(/"id"/);
    });

    it("returns null when category not found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([]);

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.uoMCategory).toBeNull();
      }
    });
  });

  describe("by name", () => {
    it("returns category when found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([baseUoMCategory]);

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.uoMCategory).toEqual(baseUoMCategory);
      }
      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0].parameters).toContain("Weight");
      expect(mock.selects[0].sql).toMatch(/"name"/);
    });

    it("returns null when category not found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([]);

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.uoMCategory).toBeNull();
      }
    });
  });
});
