import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } 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 { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(baseUnitKg);

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

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

    it("returns null when unit not found", async () => {
      const { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(undefined);

      const result = await run(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 { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(baseUnitKg);

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

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

    it("returns null when unit not found", async () => {
      const { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(undefined);

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

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