"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getIndexStatsRoute = void 0;
var _i18n = require("@kbn/i18n");
var _securitysolutionEsUtils = require("@kbn/securitysolution-es-utils");
var _lib = require("../lib");
var _build_response = require("../lib/build_response");
var _constants = require("../../common/constants");
var _common = require("../schemas/common");
var _get_index_stats = require("../schemas/get_index_stats");
/*
 * 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.
 */

const getIndexStatsRoute = (router, logger) => {
  router.versioned.get({
    path: _constants.GET_INDEX_STATS,
    access: 'internal'
  }).addVersion({
    version: _constants.INTERNAL_API_VERSION,
    validate: {
      request: {
        params: (0, _common.buildRouteValidation)(_get_index_stats.GetIndexStatsParams),
        query: (0, _common.buildRouteValidation)(_get_index_stats.GetIndexStatsQuery)
      }
    }
  }, async (context, request, response) => {
    const resp = (0, _build_response.buildResponse)(response);
    try {
      const {
        client
      } = (await context.core).elasticsearch;
      const esClient = client.asCurrentUser;
      const decodedIndexName = decodeURIComponent(request.params.pattern);
      const stats = await (0, _lib.fetchStats)(client, decodedIndexName);
      const {
        isILMAvailable,
        startDate,
        endDate
      } = request.query;
      if (isILMAvailable === true) {
        return response.ok({
          body: stats.indices
        });
      }

      /**
       * If ILM is not available, we need to fetch the available indices with the given date range.
       * `fetchAvailableIndices` returns indices that have data in the given date range.
       */
      if (startDate && endDate) {
        var _indices$aggregations, _indices$aggregations2, _indices$aggregations3;
        const decodedStartDate = decodeURIComponent(startDate);
        const decodedEndDate = decodeURIComponent(endDate);
        const indices = await (0, _lib.fetchAvailableIndices)(esClient, {
          indexPattern: decodedIndexName,
          startDate: decodedStartDate,
          endDate: decodedEndDate
        });
        const availableIndices = indices === null || indices === void 0 ? void 0 : (_indices$aggregations = indices.aggregations) === null || _indices$aggregations === void 0 ? void 0 : (_indices$aggregations2 = _indices$aggregations.index) === null || _indices$aggregations2 === void 0 ? void 0 : (_indices$aggregations3 = _indices$aggregations2.buckets) === null || _indices$aggregations3 === void 0 ? void 0 : _indices$aggregations3.reduce((acc, {
          key
        }) => {
          var _stats$indices;
          if ((_stats$indices = stats.indices) !== null && _stats$indices !== void 0 && _stats$indices[key]) {
            var _stats$indices2;
            acc[key] = (_stats$indices2 = stats.indices) === null || _stats$indices2 === void 0 ? void 0 : _stats$indices2[key];
          }
          return acc;
        }, {});
        return response.ok({
          body: availableIndices
        });
      } else {
        return resp.error({
          body: _i18n.i18n.translate('xpack.ecsDataQualityDashboard.getIndexStats.dateRangeRequiredErrorMessage', {
            defaultMessage: 'startDate and endDate are required'
          }),
          statusCode: 400
        });
      }
    } catch (err) {
      const error = (0, _securitysolutionEsUtils.transformError)(err);
      logger.error(error.message);
      return resp.error({
        body: error.message,
        statusCode: error.statusCode
      });
    }
  });
};
exports.getIndexStatsRoute = getIndexStatsRoute;