import {SCBulkResponse, SCThingType, SCUuid} from '@openstapps/core';

/**
 * Length of the index UID used for generation of its name
 */
export const INDEX_UID_LENGTH = 8;

/**
 * Matches all active indices
 */
export const ACTIVE_INDICES_ALIAS = 'stapps_active';

/**
 * Matches all inactive aliases
 */
export const INACTIVE_INDICES_ALIAS = 'stapps_inactive';

/**
 * Matches index names such as stapps_<type>_<source>_<random suffix>
 */
export const VALID_INDEX_REGEX = /^stapps_([A-z0-9_]+)_([a-z0-9-_]+)_([-a-z0-9^_]+)$/;

export interface ParsedIndexName {
  type: SCThingType;
  source: string;
  randomSuffix: string;
}

/**
 *
 */
export function parseIndexName(index: string): ParsedIndexName {
  const match = VALID_INDEX_REGEX.exec(index);
  if (!match) {
    throw new SyntaxError(`Invalid index name ${index}!`);
  }

  return {
    type: match[1] as SCThingType,
    source: match[2],
    randomSuffix: match[3],
  };
}

/**
 * Gets the index name in elasticsearch for one SCThingType
 * @param type SCThingType of data in the index
 * @param source source of data in the index
 * @param bulk bulk process which created this index
 */
export function getThingIndexName(type: SCThingType, source: string, bulk: SCBulkResponse) {
  return `stapps_${type.replaceAll(/\s+/g, '_')}_${source}_${getIndexUID(bulk.uid)}`;
}

/**
 * Returns an index that matches all indices with the specified type
 */
export function matchIndexByType(type: SCThingType, source: string) {
  return `stapps_${type.replaceAll(/\s+/g, '_')}_${source}_*`;
}

/**
 * Provides the index UID (for its name) from the bulk UID
 * @param uid Bulk UID
 */
export function getIndexUID(uid: SCUuid) {
  return uid.slice(0, Math.max(0, INDEX_UID_LENGTH));
}
