import { ok, err, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { CategoryNotFoundError } from "../lib/errors.generated";

export interface CalculateCategoryDepthInput {
  categoryId: string;
}

export async function run(db: ReadonlyDB<DB>, input: CalculateCategoryDepthInput) {
  const category = await db
    .selectFrom("ProductCategory")
    .select("parentId")
    .where("id", "=", input.categoryId)
    .executeTakeFirst();

  if (!category) {
    return err(new CategoryNotFoundError(input.categoryId));
  }

  let depth = 1;
  let currentId: string | null = category.parentId ?? null;

  while (currentId) {
    const node = await db
      .selectFrom("ProductCategory")
      .select("parentId")
      .where("id", "=", currentId)
      .executeTakeFirst();

    if (!node) break;

    depth++;
    currentId = node.parentId ?? null;
  }

  return ok({ depth });
}
