Source: server/util/monitorUtils.js

/**
 * Parse the host string and try to extract the environment being referenced
 *
 * @param host The host path (e.g. www.contoso.com)
 */
export function getEnvironmentFromHost(host) {
  if (host.toLowerCase().startsWith('local') || host.startsWith('127.0.0.1')) {
    return 'localhost';
  }

  if (!host.includes('-')) {
    return 'prd';
  }

  const firstBit = host.split('-')[0].toLowerCase();
  return firstBit === 'origin' ? 'prd' : firstBit;
}

/**
 * Validate the properties for each configuration object
 * to see if they match the expected environment in the url
 *
 * @param configArr The array containing the config objects
 * @param envFromUrl The expected environment value
 */
export function validateConfigs(configArr, envFromUrl) {
  const result = [];
  Object.keys(configArr).forEach(c => {
    const configNode = configArr[c];

    const configResult = {
      name: configNode.name,
      isOk: true,
    };

    Object.keys(configNode.properties).forEach(p => {
      const property = configNode.properties[p];

      if (!configResult.validationMessages) {
        configResult.validationMessages = [];
      }

      try {
        const envFromConfig = getEnvironmentFromHost(property.value.split('//').pop());
        if (envFromConfig !== envFromUrl && envFromUrl !== 'stg') {
          configResult.isOk = false;
          configResult.validationMessages.push(
            `${property.key} is pointing to the wrong environment - expected ${envFromUrl}, found ${envFromConfig}`,
          );
        }
      } catch (e) {
        configResult.isOk = false;
        configResult.validationMessages.push(
          `An internal error occurred while trying to verify ${property.key}`,
        );
        // eslint-disable-next-line no-console
        console.error(e);
      }
    });
    result.push(configResult);
  });
  return result;
}