"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getStorageContext = void 0;
var _utils = require("@kbn/object-versioning/lib/utils");
/*
 * 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 validateRequestVersion = (requestVersion, latestVersion) => {
  if (requestVersion === undefined) {
    // this should never happen as we have schema in place at the route level
    throw new Error('Request version missing');
  }
  const {
    result,
    value: requestVersionNumber
  } = (0, _utils.validateVersion)(requestVersion);
  if (!result) {
    throw new Error(`Invalid version [${requestVersion}]. Must be an integer.`);
  }
  if (requestVersionNumber > latestVersion) {
    throw new Error(`Invalid version. Latest version is [${latestVersion}].`);
  }
  return requestVersionNumber;
};
const getStorageContext = ({
  contentTypeId,
  version: _version,
  ctx: {
    contentRegistry,
    requestHandlerContext,
    getTransformsFactory
  }
}) => {
  const contentDefinition = contentRegistry.getDefinition(contentTypeId);
  const version = validateRequestVersion(_version, contentDefinition.version.latest);
  const storageContext = {
    requestHandlerContext,
    version: {
      request: version,
      latest: contentDefinition.version.latest
    },
    utils: {
      getTransforms: getTransformsFactory(contentTypeId, version)
    }
  };
  return storageContext;
};
exports.getStorageContext = getStorageContext;