"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.checkForUnknownDocs = void 0;
exports.getAggregatedTypesDocuments = getAggregatedTypesDocuments;
var Either = _interopRequireWildcard(require("fp-ts/lib/Either"));
var _lodash = require("lodash");
var _catch_retryable_es_client_errors = require("./catch_retryable_es_client_errors");
var _helpers = require("../model/helpers");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/** @internal */

/** @internal */

/** @internal */

/**
 * Performs a search in ES, aggregating documents by type, retrieving a bunch
 * of documents for each type.
 *
 * @internal
 * @param esClient The ES client to perform the search query
 * @param targetIndices The ES indices to target
 * @param query An optional query that can be used to filter
 * @returns A list of documents with their types
 */
async function getAggregatedTypesDocuments(esClient, targetIndices, query) {
  const params = {
    index: targetIndices,
    size: 0,
    // apply the desired filters (e.g. filter out registered types)
    query,
    // aggregate docs by type, so that we have a sneak peak of all types
    aggs: {
      typesAggregation: {
        terms: {
          // assign type __UNKNOWN__ to those documents that don't define one
          missing: '__UNKNOWN__',
          field: 'type',
          size: 1000 // collect up to 1000 types
        },

        aggs: {
          docs: {
            top_hits: {
              size: 100,
              // collect up to 100 docs for each type
              _source: {
                excludes: ['*']
              }
            }
          }
        }
      }
    }
  };
  const body = await esClient.search(params);
  if (!body.aggregations) return [];
  const {
    typesAggregation
  } = body.aggregations;
  const buckets = typesAggregation.buckets;
  const bucketsArray = Array.isArray(buckets) ? buckets : Object.values(buckets);
  return (0, _lodash.flatten)(bucketsArray.map(bucket => {
    var _bucket$docs, _bucket$docs$hits, _bucket$docs$hits$hit;
    return ((_bucket$docs = bucket.docs) === null || _bucket$docs === void 0 ? void 0 : (_bucket$docs$hits = _bucket$docs.hits) === null || _bucket$docs$hits === void 0 ? void 0 : (_bucket$docs$hits$hit = _bucket$docs$hits.hits) === null || _bucket$docs$hits$hit === void 0 ? void 0 : _bucket$docs$hits$hit.map(doc => ({
      id: doc._id,
      type: bucket.key
    }))) || [];
  }));
}
const checkForUnknownDocs = ({
  client,
  indexName,
  excludeOnUpgradeQuery,
  knownTypes
}) => () => {
  const excludeQuery = (0, _helpers.addExcludedTypesToBoolQuery)(knownTypes, excludeOnUpgradeQuery.bool);
  return getAggregatedTypesDocuments(client, indexName, excludeQuery).then(unknownDocs => {
    if (unknownDocs.length) {
      return Either.right({
        type: 'unknown_docs_found',
        unknownDocs
      });
    }
    return Either.right({});
  }).catch(_catch_retryable_es_client_errors.catchRetryableEsClientErrors);
};
exports.checkForUnknownDocs = checkForUnknownDocs;