import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseActiveItem, baseDraftItem } from "../testing/fixtures";
import { run } from "./getItem";

describe("getItem", () => {
  describe("by id", () => {
    it("returns item when found", async () => {
      const { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(baseDraftItem);

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.item).toEqual(baseDraftItem);
      }
    });

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

  describe("by sku", () => {
    it("returns item when found", async () => {
      const { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(baseDraftItem);

      const result = await run(db, { sku: "SKU-001" });

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.item).toEqual(baseDraftItem);
      }
    });

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

      const result = await run(db, { sku: "NONEXISTENT" });

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

  describe("by barcode", () => {
    it("returns item when found", async () => {
      const { db, spies } = createMockDb<DB>();
      spies.select.mockReturnValue(baseActiveItem);

      const result = await run(db, { barcode: "BAR-002" });

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.item).toEqual(baseActiveItem);
      }
    });

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

      const result = await run(db, { barcode: "NONEXISTENT" });

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