/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Logger} from '@openstapps/logger';

/**
 * Checks for invalid character in alias names and removes them
 * @param alias The alias name
 * @param uid   The UID of the current bulk (for debugging purposes)
 */
export function removeInvalidAliasChars(alias: string, uid: string | undefined): string {
  let formattedAlias = alias;

  // spaces are included in some types, replace them with underscores
  if (formattedAlias.includes(' ')) {
    formattedAlias = formattedAlias.trim();
    formattedAlias = formattedAlias.split(' ').join('_');
  }
  // List of invalid characters: https://www.elastic.co/guide/en/elasticsearch/reference/6.6/indices-create-index.html
  for (const value of ['\\', '/', '*', '?', '"', '<', '>', '|', ',', '#']) {
    if (formattedAlias.includes(value)) {
      formattedAlias = formattedAlias.replace(value, '');
      Logger.warn(`Type of the bulk ${uid} contains an invalid character '${value}'. This can lead to two bulks
        having the same alias despite having different types, as invalid characters are removed automatically.
        New alias name is "${formattedAlias}."`);
    }
  }
  for (const value of ['-', '_', '+']) {
    if (formattedAlias.charAt(0) === value) {
      formattedAlias = formattedAlias.slice(1);
      Logger.warn(`Type of the bulk ${uid} begins with '${value}'. This can lead to two bulks having the same
        alias despite having different types, as invalid characters are removed automatically.
        New alias name is "${formattedAlias}."`);
    }
  }
  if (formattedAlias === '.' || formattedAlias === '..') {
    Logger.warn(`Type of the bulk ${uid} is ${formattedAlias}. This is an invalid name, please consider using
      another one, as it will be replaced with 'alias_placeholder', which can lead to strange errors.`);

    return 'alias_placeholder';
  }
  if (formattedAlias.includes(':')) {
    Logger.warn(`Type of the bulk ${uid} contains a ':'. This isn't an issue now, but will be in future
      Elasticsearch versions!`);
  }

  return formattedAlias;
}
