"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchIndicesStats = void 0;
var _available_indices = require("./available_indices");
/*
 * 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 fetchIndicesStats = async (client, indices) => {
  const indicesStats = await client.asCurrentUser.indices.stats({
    index: await (0, _available_indices.availableIndices)(client, indices)
  });
  const searches = [];
  indices.forEach(index => {
    searches.push({
      index
    });
    searches.push({
      size: 0,
      track_total_hits: true
    });
  });
  const msearchResponse = await client.asCurrentUser.msearch({
    searches
  });
  const docCounts = msearchResponse.responses.map(response => {
    if ('error' in response) {
      return null;
    }
    const totalHits = response.hits.total;
    return totalHits.value;
  });
  return indices.map((indexName, number) => {
    var _indicesStats$indices, _docCounts$number, _indexStats$health;
    const indexStats = (_indicesStats$indices = indicesStats.indices) === null || _indicesStats$indices === void 0 ? void 0 : _indicesStats$indices[indexName];
    return {
      count: (_docCounts$number = docCounts[number]) !== null && _docCounts$number !== void 0 ? _docCounts$number : null,
      health: (_indexStats$health = indexStats === null || indexStats === void 0 ? void 0 : indexStats.health) !== null && _indexStats$health !== void 0 ? _indexStats$health : 'unknown',
      name: indexName
    };
  });
};
exports.fetchIndicesStats = fetchIndicesStats;