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

export interface DetectCategoryCircularReferenceInput {
  categoryId: string;
  newParentId: string;
}

export async function run(db: ReadonlyDB<DB>, input: DetectCategoryCircularReferenceInput) {
  const category = await db
    .selectFrom("ProductCategory")
    .select("id")
    .where("id", "=", input.categoryId)
    .executeTakeFirst();

  if (!category) {
    return err(new CategoryNotFoundError(input.categoryId));
  }

  if (input.newParentId === input.categoryId) {
    return ok({ isCircular: true });
  }

  let currentId: string | null = input.newParentId;

  while (currentId) {
    const node = await db
      .selectFrom("ProductCategory")
      .select("parentId")
      .where("id", "=", currentId)
      .executeTakeFirst();

    if (!node) break;

    currentId = node.parentId;

    if (currentId === input.categoryId) {
      return ok({ isCircular: true });
    }
  }

  return ok({ isCircular: false });
}
