"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchIndex = void 0;
require("../..");
var _searchConnectors = require("@kbn/search-connectors");
var _constants = require("../../../common/constants");
var _identify_exceptions = require("../../utils/identify_exceptions");
var _fetch_crawlers = require("../crawler/fetch_crawlers");
var _map_index_stats = require("./utils/map_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 hasInProgressSyncs = async (client, connectorId) => {
  try {
    const syncs = await client.asCurrentUser.search({
      index: _searchConnectors.CONNECTORS_JOBS_INDEX,
      query: {
        bool: {
          filter: [{
            term: {
              'connector.id': connectorId
            }
          }, {
            dis_max: {
              queries: [{
                term: {
                  status: _searchConnectors.SyncStatus.IN_PROGRESS
                }
              }, {
                term: {
                  status: _searchConnectors.SyncStatus.PENDING
                }
              }]
            }
          }]
        }
      }
    });
    const inProgress = syncs.hits.hits.some(sync => {
      var _sync$_source;
      return ((_sync$_source = sync._source) === null || _sync$_source === void 0 ? void 0 : _sync$_source.status) === _searchConnectors.SyncStatus.IN_PROGRESS;
    });
    const pending = syncs.hits.hits.some(sync => {
      var _sync$_source2;
      return ((_sync$_source2 = sync._source) === null || _sync$_source2 === void 0 ? void 0 : _sync$_source2.status) === _searchConnectors.SyncStatus.PENDING;
    });
    return {
      inProgress,
      pending
    };
  } catch (error) {
    if ((0, _identify_exceptions.isIndexNotFoundException)(error)) {
      return {
        inProgress: false,
        pending: false
      };
    }
    throw error;
  }
};
const fetchIndex = async (client, index) => {
  const indexDataResult = await client.asCurrentUser.indices.get({
    index
  });
  const indexData = indexDataResult[index];
  const {
    indices
  } = await client.asCurrentUser.indices.stats({
    index
  });
  const {
    count
  } = await client.asCurrentUser.count({
    index
  });
  if (!indices || !indices[index] || !indexData) {
    throw new Error('404');
  }
  const indexStats = indices[index];
  const connector = await (0, _searchConnectors.fetchConnectorByIndexName)(client.asCurrentUser, index);
  const hasInProgressSyncsResult = connector ? await hasInProgressSyncs(client, connector.id) : {
    inProgress: false,
    pending: false
  };
  const indexResult = {
    count,
    ...(0, _map_index_stats.mapIndexStats)(indexData, indexStats, index),
    has_in_progress_syncs: hasInProgressSyncsResult.inProgress,
    has_pending_syncs: hasInProgressSyncsResult.pending
  };
  if (connector && connector.service_type !== _constants.ENTERPRISE_SEARCH_CONNECTOR_CRAWLER_SERVICE_TYPE) {
    return {
      ...indexResult,
      connector
    };
  }
  const crawler = await (0, _fetch_crawlers.fetchCrawlerByIndexName)(client, index);
  if (crawler) {
    return {
      ...indexResult,
      connector,
      crawler
    };
  }
  return indexResult;
};
exports.fetchIndex = fetchIndex;