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

export interface DetectCircularReferenceInput {
  nodeId: string;
  newParentId: string;
}

export async function run(db: ReadonlyDB<DB>, input: DetectCircularReferenceInput) {
  if (input.newParentId === input.nodeId) {
    return ok({ isCircular: true });
  }

  // Walk up from new parent to root, checking if the moved node appears
  let ancestorId: string | null = input.newParentId;
  while (ancestorId) {
    const ancestor = await db
      .selectFrom("TaxonomyNode")
      .selectAll()
      .where("id", "=", ancestorId)
      .executeTakeFirst();

    if (!ancestor) break;

    ancestorId = ancestor.parentId;
    if (ancestorId === input.nodeId) {
      return ok({ isCircular: true });
    }
  }

  return ok({ isCircular: false });
}
