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 "./detectCircularReference";

describe("detectCircularReference", () => {
  it("detects self-reference as circular", async () => {
    const { db } = createMockDb<DB>();

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

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

  it("detects moving node under its child as circular", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseChildNode);

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

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

  it("detects moving node under its grandchild as circular", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseLeafNode).mockReturnValueOnce(baseChildNode);

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

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

  it("returns not circular for valid move", async () => {
    const secondRoot = { ...baseRootNode, id: "node-4", parentId: null };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(secondRoot);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.isCircular).toBe(false);
    }
  });

  it("returns not circular when new parent is root", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseRootNode);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.isCircular).toBe(false);
    }
  });

  it("handles broken ancestor chain gracefully (not circular)", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.isCircular).toBe(false);
    }
  });
});
