/**
 * 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 __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var context_exports = {};
__export(context_exports, {
  buildPlanSurfaceContext: () => buildPlanSurfaceContext
});
module.exports = __toCommonJS(context_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
var import_service_utils = require("../service-utils");
var import_key_registry = require("./key-registry");
async function buildPlanSurfaceContext(input, deps, options = {}) {
  const { actionName, surfaceSelector, bindKeys } = input;
  if (!surfaceSelector) {
    if (bindKeys.length) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys require surface`);
    }
    return {
      publicNodeMap: {},
      targetSummary: null,
      fingerprint: null,
      uidSet: /* @__PURE__ */ new Set(),
      keyMap: /* @__PURE__ */ new Map(),
      requestKeyMap: /* @__PURE__ */ new Map()
    };
  }
  let surfaceTarget;
  if ("key" in surfaceSelector) {
    const matchedBindKey = bindKeys.find((item) => item.key === surfaceSelector.key);
    if (!matchedBindKey) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} surface.key '${surfaceSelector.key}' must also appear in bindKeys`);
    }
    surfaceTarget = matchedBindKey.locator;
  } else {
    surfaceTarget = surfaceSelector.locator;
  }
  const surfaceResolved = await deps.resolveLocator(surfaceTarget, options);
  const rawTree = await deps.loadResolvedSurfaceTree(surfaceResolved, options.transaction);
  const publicTree = deps.stripInternalSurfaceMetaFromNodeTree(import_lodash.default.cloneDeep(rawTree));
  const publicNodeMap = (0, import_service_utils.flattenModel)(publicTree);
  const uidSet = /* @__PURE__ */ new Set([surfaceResolved.uid, ...Object.keys(publicNodeMap)]);
  const keyMap = deps.collectDeclaredKeysFromTree(rawTree);
  const requestKeyMap = /* @__PURE__ */ new Map();
  for (const bindKey of bindKeys) {
    const resolved = await deps.resolveLocator(bindKey.locator, options);
    if (!uidSet.has(resolved.uid)) {
      (0, import_errors.throwBadRequest)(
        `flowSurfaces ${actionName} bindKeys key '${bindKey.key}' must resolve inside the current surface '${surfaceResolved.uid}'`
      );
    }
    const node = publicNodeMap[resolved.uid] || (resolved.uid === surfaceResolved.uid ? publicTree : void 0);
    deps.assertBindKeyKind(actionName, bindKey, node, resolved.kind);
    const existing = requestKeyMap.get(bindKey.key) || keyMap.get(bindKey.key);
    if (existing && existing.uid !== resolved.uid && !bindKey.rebind) {
      (0, import_errors.throwConflict)(
        `flowSurfaces ${actionName} key '${bindKey.key}' is already bound to '${existing.uid}', set rebind=true to move it`,
        "FLOW_SURFACE_DECLARED_KEY_CONFLICT"
      );
    }
    requestKeyMap.set(bindKey.key, {
      key: bindKey.key,
      uid: resolved.uid,
      source: "request",
      kind: deps.buildPlanKeyKind(node, resolved.kind),
      locator: {
        uid: resolved.uid
      },
      rebind: bindKey.rebind === true,
      reboundFromUid: existing && existing.uid !== resolved.uid ? existing.uid : void 0
    });
  }
  requestKeyMap.forEach((value, key) => keyMap.set(key, value));
  keyMap.set(import_key_registry.FLOW_SURFACE_SYSTEM_KEY, {
    key: import_key_registry.FLOW_SURFACE_SYSTEM_KEY,
    uid: surfaceResolved.uid,
    source: "system",
    kind: deps.buildPlanKeyKind(publicTree, surfaceResolved.kind),
    locator: {
      uid: surfaceResolved.uid
    }
  });
  const targetSummary = deps.buildReadTargetSummary(surfaceTarget, surfaceResolved);
  const fingerprint = deps.buildSurfaceContextFingerprint({
    surfaceResolved,
    publicTree,
    keyMap
  });
  return {
    surfaceSelector,
    surfaceTarget,
    surfaceResolved,
    rawTree,
    publicTree,
    publicNodeMap,
    targetSummary,
    fingerprint,
    uidSet,
    keyMap,
    requestKeyMap
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildPlanSurfaceContext
});
