"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ValidationHelper = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _coreSavedObjectsBaseServerInternal = require("@kbn/core-saved-objects-base-server-internal");
var _coreSavedObjectsServer = require("@kbn/core-saved-objects-server");
var _coreSavedObjectsUtilsServer = require("@kbn/core-saved-objects-utils-server");
/*
 * 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 ValidationHelper {
  constructor({
    registry,
    logger,
    kibanaVersion
  }) {
    (0, _defineProperty2.default)(this, "registry", void 0);
    (0, _defineProperty2.default)(this, "logger", void 0);
    (0, _defineProperty2.default)(this, "kibanaVersion", void 0);
    (0, _defineProperty2.default)(this, "typeValidatorMap", {});
    this.registry = registry;
    this.logger = logger;
    this.kibanaVersion = kibanaVersion;
  }

  /** The `initialNamespaces` field (create, bulkCreate) is used to create an object in an initial set of spaces. */
  validateInitialNamespaces(type, initialNamespaces) {
    if (!initialNamespaces) {
      return;
    }
    if (this.registry.isNamespaceAgnostic(type)) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError('"initialNamespaces" cannot be used on space-agnostic types');
    } else if (!initialNamespaces.length) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError('"initialNamespaces" must be a non-empty array of strings');
    } else if (!this.registry.isShareable(type) && (initialNamespaces.length > 1 || initialNamespaces.includes(_coreSavedObjectsUtilsServer.ALL_NAMESPACES_STRING))) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError('"initialNamespaces" can only specify a single space when used with space-isolated types');
    }
  }

  /** The object-specific `namespaces` field (bulkGet) is used to check if an object exists in any of a given number of spaces. */
  validateObjectNamespaces(type, id, namespaces) {
    if (!namespaces) {
      return;
    }
    if (this.registry.isNamespaceAgnostic(type)) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError('"namespaces" cannot be used on space-agnostic types');
    } else if (!namespaces.length) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createGenericNotFoundError(type, id);
    } else if (!this.registry.isShareable(type) && (namespaces.length > 1 || namespaces.includes(_coreSavedObjectsUtilsServer.ALL_NAMESPACES_STRING))) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError('"namespaces" can only specify a single space when used with space-isolated types');
    }
  }

  /** Validate a migrated doc against the registered saved object type's schema. */
  validateObjectForCreate(type, doc) {
    if (!this.registry.getType(type)) {
      return;
    }
    const validator = this.getTypeValidator(type);
    try {
      validator.validate(doc);
    } catch (error) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError(error.message);
    }
  }
  getTypeValidator(type) {
    if (!this.typeValidatorMap[type]) {
      var _savedObjectType$sche, _savedObjectType$mode;
      const savedObjectType = this.registry.getType(type);
      const stackVersionSchemas = typeof (savedObjectType === null || savedObjectType === void 0 ? void 0 : savedObjectType.schemas) === 'function' ? savedObjectType.schemas() : (_savedObjectType$sche = savedObjectType === null || savedObjectType === void 0 ? void 0 : savedObjectType.schemas) !== null && _savedObjectType$sche !== void 0 ? _savedObjectType$sche : {};
      const modelVersionCreateSchemas = typeof (savedObjectType === null || savedObjectType === void 0 ? void 0 : savedObjectType.modelVersions) === 'function' ? savedObjectType.modelVersions() : (_savedObjectType$mode = savedObjectType === null || savedObjectType === void 0 ? void 0 : savedObjectType.modelVersions) !== null && _savedObjectType$mode !== void 0 ? _savedObjectType$mode : {};
      const combinedSchemas = {
        ...stackVersionSchemas
      };
      Object.entries(modelVersionCreateSchemas).reduce((map, [key, modelVersion]) => {
        var _modelVersion$schemas;
        if ((_modelVersion$schemas = modelVersion.schemas) !== null && _modelVersion$schemas !== void 0 && _modelVersion$schemas.create) {
          const virtualVersion = (0, _coreSavedObjectsBaseServerInternal.modelVersionToVirtualVersion)(key);
          combinedSchemas[virtualVersion] = modelVersion.schemas.create;
        }
        return map;
      }, {});
      this.typeValidatorMap[type] = new _coreSavedObjectsBaseServerInternal.SavedObjectsTypeValidator({
        logger: this.logger.get('type-validator'),
        type,
        validationMap: combinedSchemas,
        defaultVersion: this.kibanaVersion
      });
    }
    return this.typeValidatorMap[type];
  }

  /** This is used when objects are created. */
  validateOriginId(type, objectOrOptions) {
    if (Object.keys(objectOrOptions).includes('originId') && !this.registry.isMultiNamespace(type)) {
      throw _coreSavedObjectsServer.SavedObjectsErrorHelpers.createBadRequestError('"originId" can only be set for multi-namespace object types');
    }
  }
}
exports.ValidationHelper = ValidationHelper;