"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCurrentIndex = void 0;
var _lodash = require("lodash");
/*
 * 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.
 */

const getCurrentIndex = ({
  indices,
  aliases,
  indexPrefix
}) => {
  // if there is already a current alias pointing to an index, we reuse the index.
  if (aliases[indexPrefix] && indices.includes(aliases[indexPrefix])) {
    return aliases[indexPrefix];
  }
  const matcher = new RegExp(`^${(0, _lodash.escapeRegExp)(indexPrefix)}[_](?<counter>\\d+)$`);
  let lastCount = -1;
  indices.forEach(indexName => {
    var _match$groups;
    const match = matcher.exec(indexName);
    if (match && (_match$groups = match.groups) !== null && _match$groups !== void 0 && _match$groups.counter) {
      const suffix = parseInt(match.groups.counter, 10);
      lastCount = Math.max(lastCount, suffix);
    }
  });
  return lastCount === -1 ? undefined : `${indexPrefix}_${lastCount}`;
};
exports.getCurrentIndex = getCurrentIndex;