var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var graphLookup_exports = {};
__export(graphLookup_exports, {
  $graphLookup: () => $graphLookup
});
module.exports = __toCommonJS(graphLookup_exports);
var import_core = require("../../core");
var import_lazy = require("../../lazy");
var import_util = require("../../util");
var import_lookup = require("./lookup");
const $graphLookup = (collection, expr, options) => {
  const fromColl = (0, import_util.isString)(expr.from) ? options?.collectionResolver(expr.from) : expr.from;
  const {
    connectFromField,
    connectToField,
    as: asField,
    maxDepth,
    depthField,
    restrictSearchWithMatch: matchExpr
  } = expr;
  const pipelineExpr = matchExpr ? { pipeline: [{ $match: matchExpr }] } : {};
  return collection.map((obj) => {
    const matchObj = {};
    (0, import_util.setValue)(
      matchObj,
      connectFromField,
      (0, import_core.computeValue)(obj, expr.startWith, null, options)
    );
    let matches = [matchObj];
    let i = -1;
    const map = import_util.ValueMap.init(options.hashFunction);
    do {
      i++;
      matches = (0, import_util.flatten)(
        (0, import_lookup.$lookup)(
          (0, import_lazy.Lazy)(matches),
          {
            from: fromColl,
            localField: connectFromField,
            foreignField: connectToField,
            as: asField,
            ...pipelineExpr
          },
          options
        ).map((o) => o[asField]).value()
      );
      const oldSize = map.size;
      matches.forEach((k) => map.set(k, map.get(k) ?? i));
      if (oldSize == map.size) break;
    } while ((0, import_util.isNil)(maxDepth) || i < maxDepth);
    const result = new Array(map.size);
    let n = 0;
    map.forEach((v, k) => {
      result[n++] = Object.assign(depthField ? { [depthField]: v } : {}, k);
    });
    return { ...obj, [asField]: result };
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  $graphLookup
});
