"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.cleanUpOldFileIndices = cleanUpOldFileIndices;
var _pMap = _interopRequireDefault(require("p-map"));
/*
 * 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 INDICES_TO_CLEAN = ['.fleet-files-*', '.fleet-file-data-*', '.fleet-filedelivery-data-*', '.fleet-filedelivery-meta-*'];
const INDEX_TEMPLATE_TO_CLEAN = ['.fleet-files', '.fleet-file-data', '.fleet-filedelivery-data', '.fleet-filedelivery-meta'];

/**
 * In 8.10 upload feature moved from using index to datastreams, this function allows to clean those old indices.
 */
async function cleanUpOldFileIndices(esClient, logger) {
  try {
    // Clean indices
    await (0, _pMap.default)(INDICES_TO_CLEAN, async indiceToClean => {
      const res = await esClient.indices.get({
        index: indiceToClean
      });
      const indices = Object.keys(res);
      if (indices.length) {
        await esClient.indices.delete({
          index: indices.join(',')
        }).catch(err => {
          var _err$meta;
          // Skip not found errors
          if (((_err$meta = err.meta) === null || _err$meta === void 0 ? void 0 : _err$meta.statusCode) !== 404) {
            throw err;
          }
        });
      }
    }, {
      concurrency: 2
    });
    await esClient.indices.deleteIndexTemplate({
      name: INDEX_TEMPLATE_TO_CLEAN.join(',')
    }).catch(err => {
      var _err$meta2;
      // Skip not found errors
      if (((_err$meta2 = err.meta) === null || _err$meta2 === void 0 ? void 0 : _err$meta2.statusCode) !== 404) {
        throw err;
      }
    });
    // Clean index template
  } catch (err) {
    logger.warn(`Old fleet indices cleanup failed: ${err.message}`);
  }
}