"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.bulkGetMaintenanceWindows = bulkGetMaintenanceWindows;
var _boom = _interopRequireDefault(require("@hapi/boom"));
var _schemas = require("./schemas");
var _transforms = require("../../transforms");
var _maintenance_window = require("../../../../data/maintenance_window");
/*
 * 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 bulkGetMaintenanceWindows(context, params) {
  const {
    savedObjectsClient,
    logger
  } = context;
  const {
    ids
  } = params;
  try {
    _schemas.bulkGetMaintenanceWindowsParamsSchema.validate(params);
  } catch (error) {
    throw _boom.default.badRequest(`Error validating bulk get maintenance window data - ${error.message}`);
  }
  const bulkGetObjects = ids.map(id => ({
    id
  }));
  try {
    const {
      saved_objects: savedObjects
    } = await (0, _maintenance_window.bulkGetMaintenanceWindowSo)({
      objects: bulkGetObjects,
      savedObjectsClient
    });
    const maintenanceWindows = [];
    const errors = [];
    savedObjects.forEach(so => {
      if (so.error) {
        errors.push({
          id: so.id,
          error: so.error.error,
          message: so.error.message,
          statusCode: so.error.statusCode
        });
      } else {
        maintenanceWindows.push((0, _transforms.transformMaintenanceWindowAttributesToMaintenanceWindow)({
          id: so.id,
          attributes: so.attributes
        }));
      }
    });
    return {
      maintenanceWindows,
      errors
    };
  } catch (e) {
    const errorMessage = `Failed to bulk get maintenance window for ids: ${ids}, Error: ${e}`;
    logger.error(errorMessage);
    throw _boom.default.boomify(e, {
      message: errorMessage
    });
  }
}