import { describe, expect, it } from "vitest";
import { collectSubtree } from "../../convex/_utils/documentTree";

describe("collectSubtree", () => {
  it("会收集根节点及其所有后代", () => {
    const rows = [
      { id: "A", parent_id: null },
      { id: "B", parent_id: "A" },
      { id: "C", parent_id: "B" },
      { id: "D", parent_id: "A" },
      { id: "E", parent_id: null },
    ] as const;

    const subtree = collectSubtree(rows, "A");
    expect(new Set(subtree.map((r) => r.id))).toEqual(new Set(["A", "B", "C", "D"]));
  });

  it("根节点不存在时返回空数组", () => {
    const rows = [{ id: "A", parent_id: null }] as const;
    expect(collectSubtree(rows, "missing")).toEqual([]);
  });

  it("存在环时不会死循环", () => {
    const rows = [
      { id: "A", parent_id: "B" },
      { id: "B", parent_id: "A" },
      { id: "C", parent_id: null },
    ] as const;

    const subtree = collectSubtree(rows, "A");
    expect(new Set(subtree.map((r) => r.id))).toEqual(new Set(["A", "B"]));
  });
});

