import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { CategoryNotFoundError } from "../lib/errors.generated";
import { run } from "./detectCategoryCircularReference";

describe("detectCategoryCircularReference", () => {
  it("returns CategoryNotFoundError when category does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { categoryId: "nonexistent", newParentId: "category-2" });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CategoryNotFoundError);
    }
  });

  it("detects self-reference as circular", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({ id: "category-1" });

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

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

  it("detects circular reference when moving node under its descendant", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce({ id: "category-1" })
      .mockReturnValueOnce({ parentId: "category-1" });

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

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

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

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

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

  it("returns not circular when ancestor chain is broken", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({ id: "category-1" }).mockReturnValueOnce(undefined);

    const result = await run(db, {
      categoryId: "category-1",
      newParentId: "category-orphan",
    });

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