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

describe("calculateCategoryDepth", () => {
  it("returns depth 1 for root category", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ parentId: null }]);

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

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

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

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

  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" });

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

  it("returns partial depth when ancestor in chain is not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ parentId: "category-1" }], []);

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

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