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

export interface DetectBillOfMaterialCircularReferenceInput {
  companyId: string;
  parentItemId: string;
  childItemId: string;
}

export async function run(db: ReadonlyDB<DB>, input: DetectBillOfMaterialCircularReferenceInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError("companyId"));
  }

  if (!input.parentItemId || !input.childItemId) {
    return err(new ItemReferenceRequiredError("parentItemId and childItemId"));
  }

  // If child === parent, immediate circular reference
  if (input.childItemId === input.parentItemId) {
    return ok({
      hasCircularReference: true,
      path: [input.parentItemId, input.childItemId],
    });
  }

  // BFS from childItemId through active BOMs to see if any path reaches parentItemId
  const visited = new Set<string>();
  const queue: { itemId: string; path: string[] }[] = [
    { itemId: input.childItemId, path: [input.parentItemId, input.childItemId] },
  ];

  while (queue.length > 0) {
    const current = queue.shift()!;

    if (visited.has(current.itemId)) {
      continue;
    }
    visited.add(current.itemId);

    // Find active BOMs where this item is the parent
    const activeBoms = await db
      .selectFrom("BillOfMaterial")
      .select("id")
      .where("parentItemId", "=", current.itemId)
      .where("companyId", "=", input.companyId)
      .where("status", "=", "ACTIVE")
      .execute();

    if (activeBoms.length === 0) {
      continue;
    }

    const bomIds = activeBoms.map((b) => b.id);

    // Find subassembly lines for these BOMs
    const subassemblyLines = await db
      .selectFrom("BillOfMaterialLine")
      .select("itemId")
      .where("billOfMaterialId", "in", bomIds)
      .where("isSubassembly", "=", true)
      .execute();

    for (const line of subassemblyLines) {
      const newPath = [...current.path, line.itemId];

      if (line.itemId === input.parentItemId) {
        return ok({ hasCircularReference: true, path: newPath });
      }

      if (!visited.has(line.itemId)) {
        queue.push({ itemId: line.itemId, path: newPath });
      }
    }
  }

  return ok({ hasCircularReference: false, path: null });
}
