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

describe("getTaxonomyNodeChildren", () => {
  it("returns children when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChildNode]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.children).toEqual([baseChildNode]);
    }

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

  it("returns multiple children", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChildNode, baseLeafNode]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.children).toHaveLength(2);
    }

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

  it("returns empty array when no children", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.children).toEqual([]);
    }

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