"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EncryptionHelper = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
/*
 * 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.
 */

class EncryptionHelper {
  constructor({
    securityExtension,
    encryptionExtension
  }) {
    (0, _defineProperty2.default)(this, "securityExtension", void 0);
    (0, _defineProperty2.default)(this, "encryptionExtension", void 0);
    this.securityExtension = securityExtension;
    this.encryptionExtension = encryptionExtension;
  }
  async optionallyEncryptAttributes(type, id, namespaceOrNamespaces, attributes) {
    var _this$encryptionExten;
    if (!((_this$encryptionExten = this.encryptionExtension) !== null && _this$encryptionExten !== void 0 && _this$encryptionExten.isEncryptableType(type))) {
      return attributes;
    }
    const namespace = Array.isArray(namespaceOrNamespaces) ? namespaceOrNamespaces[0] : namespaceOrNamespaces;
    const descriptor = {
      type,
      id,
      namespace
    };
    return this.encryptionExtension.encryptAttributes(descriptor, attributes);
  }
  async optionallyDecryptAndRedactSingleResult(object, typeMap, originalAttributes) {
    var _this$encryptionExten2;
    if ((_this$encryptionExten2 = this.encryptionExtension) !== null && _this$encryptionExten2 !== void 0 && _this$encryptionExten2.isEncryptableType(object.type)) {
      object = await this.encryptionExtension.decryptOrStripResponseAttributes(object, originalAttributes);
    }
    if (typeMap) {
      return this.securityExtension.redactNamespaces({
        typeMap,
        savedObject: object
      });
    }
    return object;
  }
  async optionallyDecryptAndRedactBulkResult(response, typeMap, originalObjects) {
    const modifiedObjects = await Promise.all(response.saved_objects.map(async (object, index) => {
      if (object.error) {
        // If the bulk operation failed, the object will not have an attributes field at all, it will have an error field instead.
        // In this case, don't attempt to decrypt, just return the object.
        return object;
      }
      const originalAttributes = originalObjects === null || originalObjects === void 0 ? void 0 : originalObjects[index].attributes;
      return await this.optionallyDecryptAndRedactSingleResult(object, typeMap, originalAttributes);
    }));
    return {
      ...response,
      saved_objects: modifiedObjects
    };
  }
}
exports.EncryptionHelper = EncryptionHelper;