"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.performBulkResolve = void 0;
var _utils = require("./utils");
var _internal_bulk_resolve = require("./internals/internal_bulk_resolve");
var _increment_counter_internal = require("./internals/increment_counter_internal");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const performBulkResolve = async ({
  objects,
  options
}, apiExecutionContext) => {
  const {
    registry,
    helpers,
    allowedTypes,
    client,
    migrator,
    serializer,
    extensions = {}
  } = apiExecutionContext;
  const {
    common: commonHelper
  } = helpers;
  const {
    securityExtension,
    encryptionExtension
  } = extensions;
  const namespace = commonHelper.getCurrentNamespace(options.namespace);
  const {
    resolved_objects: bulkResults
  } = await (0, _internal_bulk_resolve.internalBulkResolve)({
    registry,
    allowedTypes,
    client,
    migrator,
    serializer,
    getIndexForType: commonHelper.getIndexForType.bind(commonHelper),
    incrementCounterInternal: (type, id, counterFields, opts = {}) => (0, _increment_counter_internal.incrementCounterInternal)({
      type,
      id,
      counterFields,
      options: opts
    }, apiExecutionContext),
    encryptionExtension,
    securityExtension,
    objects,
    options: {
      ...options,
      namespace
    }
  });
  const resolvedObjects = bulkResults.map(result => {
    // extract payloads from saved object errors
    if ((0, _internal_bulk_resolve.isBulkResolveError)(result)) {
      const errorResult = result;
      const {
        type,
        id,
        error
      } = errorResult;
      return {
        saved_object: {
          type,
          id,
          error: (0, _utils.errorContent)(error)
        },
        outcome: 'exactMatch'
      };
    }
    return result;
  });
  return {
    resolved_objects: resolvedObjects
  };
};
exports.performBulkResolve = performBulkResolve;