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

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

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.node).toEqual(baseRootNode);
      }

      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0]?.parameters).toContain("node-1");
      expect(mock.selects[0]?.sql).toMatch(/"id"/);
    });

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

      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0]?.parameters).toContain("nonexistent");
      expect(mock.selects[0]?.sql).toMatch(/"id"/);
    });
  });

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

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

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.node).toEqual(baseRootNode);
      }

      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0]?.parameters).toContain("ELECTRONICS");
      expect(mock.selects[0]?.sql).toMatch(/"code"/);
    });

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

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

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

      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0]?.parameters).toContain("NONEXISTENT");
      expect(mock.selects[0]?.sql).toMatch(/"code"/);
    });
  });
});
