"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.coreVersionTransformTypes = exports.assertValidCoreVersion = exports.applyVersion = void 0;
exports.maxVersion = maxVersion;
var _semver = _interopRequireDefault(require("semver"));
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _types = require("../types");
/*
 * 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.
 */

/** transform types using `coreMigrationVersion` and not `typeMigrationVersion` */
const coreVersionTransformTypes = [_types.TransformType.Core, _types.TransformType.Reference];

/**
 * Apply the version of the given {@link Transform | transform} to the given {@link SavedObjectUnsanitizedDoc | document}.
 * Will update `coreMigrationVersion` or `typeMigrationVersion` depending on the type of the transform.
 */
exports.coreVersionTransformTypes = coreVersionTransformTypes;
const applyVersion = ({
  document,
  transform
}) => {
  return {
    ...document,
    ...(coreVersionTransformTypes.includes(transform.transformType) ? {
      coreMigrationVersion: transform.version
    } : {
      typeMigrationVersion: transform.version
    })
  };
};

/**
 * Asserts the document's core version is valid and not greater than the current Kibana version.
 * Hence, the object does not belong to a more recent version of Kibana.
 */
exports.applyVersion = applyVersion;
const assertValidCoreVersion = ({
  kibanaVersion,
  document
}) => {
  const {
    id,
    coreMigrationVersion
  } = document;
  if (!coreMigrationVersion) {
    return;
  }
  if (!_semver.default.valid(coreMigrationVersion)) {
    throw _boom.default.badData(`Document "${id}" has an invalid "coreMigrationVersion" [${coreMigrationVersion}]. This must be a semver value.`, document);
  }
  if (_semver.default.gt(coreMigrationVersion, kibanaVersion)) {
    throw _boom.default.badData(`Document "${id}" has a "coreMigrationVersion" which belongs to a more recent version` + ` of Kibana [${coreMigrationVersion}]. The current version is [${kibanaVersion}].`, document);
  }
};
exports.assertValidCoreVersion = assertValidCoreVersion;
function maxVersion(a, b) {
  if (!a) {
    return b;
  }
  if (!b) {
    return a;
  }
  return _semver.default.gt(a, b) ? a : b;
}