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 lookup_exports = {};
__export(lookup_exports, {
  $lookup: () => $lookup
});
module.exports = __toCommonJS(lookup_exports);
var import_aggregator = require("../../aggregator");
var import_core = require("../../core");
var import_util = require("../../util");
const $lookup = (collection, expr, options) => {
  const joinColl = (0, import_util.isString)(expr.from) ? options?.collectionResolver(expr.from) : expr.from;
  const { let: letExpr, pipeline, foreignField, localField } = expr;
  const subQueryPipeline = pipeline || [];
  let lookupEq = (_) => [true, []];
  if (foreignField && localField) {
    const map = import_util.ValueMap.init(options.hashFunction);
    for (const doc of joinColl) {
      (0, import_util.ensureArray)((0, import_util.resolve)(doc, foreignField) ?? null).forEach((v) => {
        const xs = map.get(v);
        const arr = xs ?? [];
        arr.push(doc);
        if (arr !== xs) map.set(v, arr);
      });
    }
    lookupEq = (o) => {
      const local = (0, import_util.resolve)(o, localField) ?? null;
      if ((0, import_util.isArray)(local)) {
        if (subQueryPipeline.length) {
          return [local.some((v) => map.has(v)), null];
        }
        const result2 = Array.from(
          new Set((0, import_util.flatten)(local.map((v) => map.get(v), options.hashFunction)))
        );
        return [result2.length > 0, result2];
      }
      const result = map.get(local) ?? null;
      return [result !== null, result ?? []];
    };
    if (subQueryPipeline.length === 0) {
      return collection.map((obj) => {
        return {
          ...obj,
          [expr.as]: lookupEq(obj).pop()
        };
      });
    }
  }
  const agg = new import_aggregator.Aggregator(subQueryPipeline, options);
  const opts = { ...options };
  return collection.map((obj) => {
    const vars = (0, import_core.computeValue)(obj, letExpr, null, options);
    opts.variables = { ...options.variables, ...vars };
    const [ok, res] = lookupEq(obj);
    return {
      ...obj,
      [expr.as]: ok ? agg.run(joinColl, opts) : res
    };
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  $lookup
});
