import type { DB } from "../generated/kysely-tailordb";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface CalculateNodeDepthInput {
  nodeId: string;
}

export async function run(db: ReadonlyDB<DB>, input: CalculateNodeDepthInput) {
  let depth = 1;
  let currentId: string | null = input.nodeId;

  while (currentId) {
    const node = await db
      .selectFrom("TaxonomyNode")
      .selectAll()
      .where("id", "=", currentId)
      .executeTakeFirst();

    if (!node) break;

    if (!node.parentId) break;

    depth++;
    currentId = node.parentId;
  }

  return ok({ depth });
}
