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

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

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

  it("returns depth 2 for child of root", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseChildNode).mockReturnValueOnce(baseRootNode);

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

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

  it("returns depth 3 for grandchild of root", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce(baseLeafNode)
      .mockReturnValueOnce(baseChildNode)
      .mockReturnValueOnce(baseRootNode);

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

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

  it("returns depth 1 when node not found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

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

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

  it("handles broken ancestor chain gracefully", async () => {
    const brokenNode = { ...baseChildNode, parentId: "missing-parent" };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(brokenNode).mockReturnValueOnce(undefined);

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

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