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

export interface DetectDepartmentCircularReferenceInput {
  departmentId: string;
  newParentId: string;
}

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

  let ancestorId: string | null = input.newParentId;
  while (ancestorId) {
    const ancestor = await db
      .selectFrom("Department")
      .selectAll()
      .where("id", "=", ancestorId)
      .executeTakeFirst();
    if (!ancestor) return ok({ isCircular: false });
    ancestorId = ancestor.parentDepartmentId;
    if (ancestorId === input.departmentId) return ok({ isCircular: true });
  }

  return ok({ isCircular: false });
}
