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

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

/**
 * Function: detectCircularReference
 *
 * Validates that reparenting an account group would not create a circular
 * reference in the tree hierarchy.
 */
export async function run(db: ReadonlyDB<DB>, input: DetectCircularReferenceInput) {
  const { groupId, newParentId } = input;

  // Self-reference is always circular
  if (newParentId === groupId) {
    return ok({ isCircular: true });
  }

  // Walk up the ancestor chain from newParentId
  let ancestorId: string | null = newParentId;

  while (ancestorId) {
    const ancestor = await db
      .selectFrom("AccountGroup")
      .selectAll()
      .where("id", "=", ancestorId)
      .executeTakeFirst();

    if (!ancestor) {
      // Broken chain — no cycle
      return ok({ isCircular: false });
    }

    ancestorId = ancestor.parentAccountGroupId;

    if (ancestorId === groupId) {
      return ok({ isCircular: true });
    }
  }

  return ok({ isCircular: false });
}
