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

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

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

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

    it("returns null when unit 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.unit).toBeNull();
      }
    });
  });

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

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.unit).toEqual(baseUnitKg);
      }
      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0].parameters).toContain("kg");
      expect(mock.selects[0].sql).toMatch(/"symbol"/);
    });

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

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

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