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

export interface CalculateSubtreeDepthInput {
  nodeId: string;
}

async function getSubtreeDepth(db: ReadonlyDB<DB>, nodeId: string): Promise<number> {
  const children = await db
    .selectFrom("TaxonomyNode")
    .selectAll()
    .where("parentId", "=", nodeId)
    .execute();

  if (!children || children.length === 0) return 1;

  let maxChildDepth = 0;
  for (const child of children) {
    const childDepth = await getSubtreeDepth(db, child.id);
    if (childDepth > maxChildDepth) maxChildDepth = childDepth;
  }

  return 1 + maxChildDepth;
}

export async function run(db: ReadonlyDB<DB>, input: CalculateSubtreeDepthInput) {
  const depth = await getSubtreeDepth(db, input.nodeId);
  return ok({ depth });
}
