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

describe("calculateNodeDepth", () => {
  it("returns depth 1 for root node", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseRootNode]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.depth).toBe(1);
    }

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

  it("returns depth 2 for child of root", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChildNode], [baseRootNode]);

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

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

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

  it("returns depth 3 for grandchild of root", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseLeafNode], [baseChildNode], [baseRootNode]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.depth).toBe(3);
    }

    expect(mock.selects).toHaveLength(3);
    expect(mock.selects[0]?.parameters).toContain("node-3");
  });

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.depth).toBe(1);
    }

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

  it("handles broken ancestor chain gracefully", async () => {
    const brokenNode = { ...baseChildNode, parentId: "missing-parent" };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([brokenNode], []);

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

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

    expect(mock.selects).toHaveLength(2);
    expect(mock.selects[1]?.parameters).toContain("missing-parent");
  });
});
