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

describe("calculateCategoryDepth", () => {
  it("returns depth 1 for root category", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({ parentId: null });

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce({ parentId: "category-1" })
      .mockReturnValueOnce({ parentId: null });

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select
      .mockReturnValueOnce({ parentId: "category-2" })
      .mockReturnValueOnce({ parentId: "category-1" })
      .mockReturnValueOnce({ parentId: null });

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce({ parentId: "category-1" }).mockReturnValueOnce(undefined);

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

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