/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 utils_exports = {};
__export(utils_exports, {
  prefetchRecordsForResolve: () => prefetchRecordsForResolve
});
module.exports = __toCommonJS(utils_exports);
var import_registry = require("./registry");
var import_selects = require("./selects");
var import_records = require("./records");
async function prefetchRecordsForResolve(koaCtx, items) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  try {
    const log = (_b = (_a = koaCtx.app) == null ? void 0 : _a.logger) == null ? void 0 : _b.child({ module: "plugin-flow-engine", submodule: "variables.prefetch" });
    const groupMap = /* @__PURE__ */ new Map();
    const ensureGroup = (dataSourceKey, collection, filterByTk, strictSelects, opts) => {
      const groupKey = JSON.stringify({
        ds: dataSourceKey,
        collection,
        tk: filterByTk,
        f: Array.isArray(opts == null ? void 0 : opts.fields) ? [...opts.fields].sort() : void 0,
        a: Array.isArray(opts == null ? void 0 : opts.appends) ? [...opts.appends].sort() : void 0
      });
      let group = groupMap.get(groupKey);
      if (!group) {
        group = {
          dataSourceKey,
          collection,
          filterByTk,
          strictSelects,
          fields: /* @__PURE__ */ new Set(),
          appends: /* @__PURE__ */ new Set()
        };
        groupMap.set(groupKey, group);
      }
      return group;
    };
    const normalizeNestedSeg = (segment) => /^\d+$/.test(segment) ? `[${segment}]` : segment;
    for (const it of items) {
      const template = (it == null ? void 0 : it.template) ?? {};
      const contextParams = (it == null ? void 0 : it.contextParams) || {};
      const usage = import_registry.variables.extractUsage(template);
      for (const [cpKey, recordParams] of Object.entries(contextParams)) {
        const parts = String(cpKey).split(".");
        const varName = parts[0];
        const nestedSeg = parts.slice(1).join(".");
        const paths = (usage == null ? void 0 : usage[varName]) || [];
        if (!paths.length) continue;
        const segNorm = nestedSeg ? normalizeNestedSeg(nestedSeg) : "";
        const remainders = [];
        for (const p of paths) {
          if (!segNorm) remainders.push(p);
          else if (p === segNorm) remainders.push("");
          else if (p.startsWith(`${segNorm}.`) || p.startsWith(`${segNorm}[`))
            remainders.push(p.slice(segNorm.length + 1));
        }
        if (!remainders.length) continue;
        const dataSourceKey = (recordParams == null ? void 0 : recordParams.dataSourceKey) || "main";
        const collection = recordParams == null ? void 0 : recordParams.collection;
        const filterByTk = recordParams == null ? void 0 : recordParams.filterByTk;
        if (!collection || typeof filterByTk === "undefined") continue;
        const explicitFields = recordParams == null ? void 0 : recordParams.fields;
        const explicitAppends = recordParams == null ? void 0 : recordParams.appends;
        const hasExplicit = Array.isArray(explicitFields) || Array.isArray(explicitAppends);
        const group = ensureGroup(dataSourceKey, collection, filterByTk, hasExplicit, {
          fields: hasExplicit ? explicitFields : void 0,
          appends: hasExplicit ? explicitAppends : void 0
        });
        if (hasExplicit) {
          const fixed2 = (0, import_selects.adjustSelectsForCollection)(koaCtx, dataSourceKey, collection, explicitFields, explicitAppends);
          (_c = fixed2.fields) == null ? void 0 : _c.forEach((f) => group.fields.add(f));
          (_d = fixed2.appends) == null ? void 0 : _d.forEach((a) => group.appends.add(a));
          continue;
        }
        let { generatedAppends, generatedFields } = (0, import_registry.inferSelectsFromUsage)(remainders);
        const fixed = (0, import_selects.adjustSelectsForCollection)(koaCtx, dataSourceKey, collection, generatedFields, generatedAppends);
        generatedFields = fixed.fields;
        generatedAppends = fixed.appends;
        if (generatedFields == null ? void 0 : generatedFields.length) generatedFields.forEach((f) => group.fields.add(f));
        if (generatedAppends == null ? void 0 : generatedAppends.length) generatedAppends.forEach((a) => group.appends.add(a));
      }
    }
    if (!groupMap.size) return;
    const stateObj = koaCtx.state;
    if (stateObj && !stateObj["__varResolveBatchCache"]) {
      stateObj["__varResolveBatchCache"] = /* @__PURE__ */ new Map();
    }
    const cache = (_e = koaCtx.state) == null ? void 0 : _e["__varResolveBatchCache"];
    for (const { dataSourceKey, collection, filterByTk, strictSelects, fields, appends } of groupMap.values()) {
      try {
        const ds = koaCtx.app.dataSourceManager.get(dataSourceKey);
        const cm = ds.collectionManager;
        if (!(cm == null ? void 0 : cm.db)) continue;
        const repo = cm.db.getRepository(collection);
        const collectionInfo = repo == null ? void 0 : repo.collection;
        const filterTargetKey = collectionInfo == null ? void 0 : collectionInfo.filterTargetKey;
        const modelInfo = (_f = repo.collection) == null ? void 0 : _f.model;
        const pkAttr = modelInfo == null ? void 0 : modelInfo.primaryKeyAttribute;
        const rawAttributes = (modelInfo == null ? void 0 : modelInfo.rawAttributes) || void 0;
        const pkIsValid = !!(pkAttr && rawAttributes && Object.prototype.hasOwnProperty.call(rawAttributes, pkAttr));
        const fldBase = fields.size ? Array.from(fields).sort() : void 0;
        const extraKeys = (0, import_records.getExtraKeyFieldsForSelect)(filterByTk, {
          filterTargetKey,
          pkAttr,
          pkIsValid,
          rawAttributes
        });
        const effectiveExtras = strictSelects && Array.isArray(extraKeys) && extraKeys.length ? extraKeys.filter((k) => k === pkAttr) : extraKeys;
        const fld = (0, import_records.mergeFieldsWithExtras)(fldBase, effectiveExtras);
        const app = appends.size ? Array.from(appends).sort() : void 0;
        const json = await (0, import_records.fetchRecordOrRecordsJson)(repo, {
          filterByTk,
          fields: fld,
          appends: app,
          filterTargetKey,
          pkAttr,
          pkIsValid
        });
        if (cache) {
          const key = JSON.stringify({ ds: dataSourceKey, c: collection, tk: filterByTk, f: fld, a: app });
          cache.set(key, json);
        }
      } catch (e) {
        log == null ? void 0 : log.debug("[variables.resolve] prefetch query error", {
          ds: dataSourceKey,
          collection,
          tk: filterByTk,
          error: (e == null ? void 0 : e.message) || String(e)
        });
      }
    }
  } catch (e) {
    (_i = (_h = (_g = koaCtx.app) == null ? void 0 : _g.logger) == null ? void 0 : _h.child({ module: "plugin-flow-engine", submodule: "variables.prefetch" })) == null ? void 0 : _i.debug("[variables.resolve] prefetch fatal error", { error: (e == null ? void 0 : e.message) || String(e) });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  prefetchRecordsForResolve
});
