"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createMaintenanceWindow = createMaintenanceWindow;
var _moment = _interopRequireDefault(require("moment"));
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _server = require("@kbn/core/server");
var _generate_maintenance_window_events = require("../../lib/generate_maintenance_window_events");
var _transforms = require("../../transforms");
var _maintenance_window = require("../../../../data/maintenance_window");
var _schemas = require("./schemas");
/*
 * 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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

async function createMaintenanceWindow(context, params) {
  const {
    data
  } = params;
  const {
    savedObjectsClient,
    getModificationMetadata,
    logger
  } = context;
  const {
    title,
    duration,
    rRule,
    categoryIds
  } = data;
  try {
    _schemas.createMaintenanceWindowParamsSchema.validate(params);
  } catch (error) {
    throw _boom.default.badRequest(`Error validating create maintenance window data - ${error.message}`);
  }
  const id = _server.SavedObjectsUtils.generateId();
  const expirationDate = (0, _moment.default)().utc().add(1, 'year').toISOString();
  const modificationMetadata = await getModificationMetadata();
  const events = (0, _generate_maintenance_window_events.generateMaintenanceWindowEvents)({
    rRule,
    expirationDate,
    duration
  });
  const maintenanceWindowAttributes = (0, _transforms.transformMaintenanceWindowToMaintenanceWindowAttributes)({
    title,
    enabled: true,
    expirationDate,
    categoryIds,
    rRule: rRule,
    duration,
    events,
    ...modificationMetadata
  });
  try {
    const result = await (0, _maintenance_window.createMaintenanceWindowSo)({
      savedObjectsClient,
      maintenanceWindowAttributes,
      savedObjectsCreateOptions: {
        id
      }
    });
    return (0, _transforms.transformMaintenanceWindowAttributesToMaintenanceWindow)({
      attributes: result.attributes,
      id: result.id
    });
  } catch (e) {
    const errorMessage = `Failed to create maintenance window, Error: ${e}`;
    logger.error(errorMessage);
    throw _boom.default.boomify(e, {
      message: errorMessage
    });
  }
}