import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ id: "category-1" }]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ id: "category-1" }], [{ parentId: "category-1" }]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ id: "category-3" }], [{ parentId: null }]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ id: "category-1" }], []);

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

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