"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.validateCATrustedFingerPrint = validateCATrustedFingerPrint;
exports.validateESHosts = validateESHosts;
exports.validateKafkaClientId = validateKafkaClientId;
exports.validateKafkaDefaultTopic = validateKafkaDefaultTopic;
exports.validateKafkaHeaders = validateKafkaHeaders;
exports.validateKafkaHosts = validateKafkaHosts;
exports.validateKafkaPartitioningGroupEvents = validateKafkaPartitioningGroupEvents;
exports.validateKafkaPassword = validateKafkaPassword;
exports.validateKafkaTopics = validateKafkaTopics;
exports.validateKafkaUsername = validateKafkaUsername;
exports.validateLogstashHosts = validateLogstashHosts;
exports.validateName = validateName;
exports.validateSSLCertificate = validateSSLCertificate;
exports.validateSSLKey = validateSSLKey;
exports.validateYamlConfig = validateYamlConfig;
var _i18n = require("@kbn/i18n");
var _jsYaml = require("js-yaml");
/*
 * 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.
 */

function validateKafkaHosts(value) {
  const res = [];
  const urlIndexes = {};
  value.forEach((val, idx) => {
    if (!val) {
      res.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHostFieldRequiredError', {
          defaultMessage: 'Host is required'
        })
      });
      return;
    }

    // Split the URL into parts based on ":"
    const urlParts = val.split(':');
    if (urlParts.length !== 2 || !urlParts[0] || !urlParts[1]) {
      res.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHostPortError', {
          defaultMessage: 'Invalid format. Expected "host:port" without protocol.'
        }),
        index: idx
      });
      return;
    }

    // Validate that the port is a valid number
    const port = parseInt(urlParts[1], 10);
    if (isNaN(port) || port < 1 || port > 65535) {
      res.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaPortError', {
          defaultMessage: 'Invalid port number. Expected a number between 1 and 65535'
        }),
        index: idx
      });
    }
    const curIndexes = urlIndexes[val] || [];
    urlIndexes[val] = [...curIndexes, idx];
  });
  Object.values(urlIndexes).filter(({
    length
  }) => length > 1).forEach(indexes => {
    indexes.forEach(index => res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHostDuplicateError', {
        defaultMessage: 'Duplicate URL'
      }),
      index
    }));
  });
  if (value.length === 0) {
    res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHostRequiredError', {
        defaultMessage: 'Host is required'
      })
    });
  }
  if (res.length) {
    return res;
  }
}
function validateESHosts(value) {
  const res = [];
  const urlIndexes = {};
  value.forEach((val, idx) => {
    try {
      if (!val) {
        throw new Error('Host URL required');
      }
      const urlParsed = new URL(val);
      if (!['http:', 'https:'].includes(urlParsed.protocol)) {
        throw new Error('Invalid protocol');
      }
    } catch (error) {
      res.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.elasticHostError', {
          defaultMessage: 'Invalid URL'
        }),
        index: idx
      });
    }
    const curIndexes = urlIndexes[val] || [];
    urlIndexes[val] = [...curIndexes, idx];
  });
  Object.values(urlIndexes).filter(({
    length
  }) => length > 1).forEach(indexes => {
    indexes.forEach(index => res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.elasticHostDuplicateError', {
        defaultMessage: 'Duplicate URL'
      }),
      index
    }));
  });
  if (value.length === 0) {
    res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.elasticUrlRequiredError', {
        defaultMessage: 'URL is required'
      })
    });
  }
  if (res.length) {
    return res;
  }
}
function validateLogstashHosts(value) {
  const res = [];
  const urlIndexes = {};
  value.forEach((val, idx) => {
    try {
      if (val.match(/^http([s]){0,1}:\/\//)) {
        res.push({
          message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.logstashHostProtocolError', {
            defaultMessage: 'Host address must begin with a domain name or IP address'
          }),
          index: idx
        });
        return;
      }
      const url = new URL(`http://${val}`);
      if (url.host !== val) {
        throw new Error('Invalid host');
      }
    } catch (error) {
      if (val.length === 0) {
        res.push({
          message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.logstashHostRequiredError', {
            defaultMessage: 'Host is required'
          }),
          index: idx
        });
      } else {
        res.push({
          message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.logstashHostError', {
            defaultMessage: 'Invalid Host'
          }),
          index: idx
        });
      }
    }
    const curIndexes = urlIndexes[val] || [];
    urlIndexes[val] = [...curIndexes, idx];
  });
  Object.values(urlIndexes).filter(({
    length
  }) => length > 1).forEach(indexes => {
    indexes.forEach(index => res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.logstashHostDuplicateError', {
        defaultMessage: 'Duplicate Host'
      }),
      index
    }));
  });
  if (value.length === 0) {
    res.push({
      message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.logstashHostRequiredError', {
        defaultMessage: 'Host is required'
      })
    });
  }
  if (res.length) {
    return res;
  }
}
function validateYamlConfig(value) {
  try {
    (0, _jsYaml.safeLoad)(value);
    return;
  } catch (error) {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.invalidYamlFormatErrorMessage', {
      defaultMessage: 'Invalid YAML: {reason}',
      values: {
        reason: error.message
      }
    })];
  }
}
function validateName(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.nameIsRequiredErrorMessage', {
      defaultMessage: 'Name is required'
    })];
  }
}
function validateKafkaUsername(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaUsernameIsRequired', {
      defaultMessage: 'Username is required'
    })];
  }
}
function validateKafkaPassword(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaPasswordIsRequired', {
      defaultMessage: 'Password is required'
    })];
  }
}
function validateCATrustedFingerPrint(value) {
  if (value !== '' && !value.match(/^[a-zA-Z0-9]+$/)) {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.caTrusterdFingerprintInvalidErrorMessage', {
      defaultMessage: 'CA trusted fingerprint should be valid HEX encoded SHA-256 of a CA certificate'
    })];
  }
}
function validateSSLCertificate(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.sslCertificateRequiredErrorMessage', {
      defaultMessage: 'SSL certificate is required'
    })];
  }
}
function validateSSLKey(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.sslKeyRequiredErrorMessage', {
      defaultMessage: 'SSL key is required'
    })];
  }
}
function validateKafkaDefaultTopic(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaDefaultTopicRequiredMessage', {
      defaultMessage: 'Default topic is required'
    })];
  }
}
function validateKafkaClientId(value) {
  const regex = /^[A-Za-z0-9._-]+$/;
  return regex.test(value) ? undefined : [_i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaClientIdFormattingMessage', {
    defaultMessage: 'Client ID is invalid. Only letters, numbers, dots, underscores, and dashes are allowed.'
  })];
}
function validateKafkaPartitioningGroupEvents(value) {
  const regex = /^[0-9]+$/;
  return regex.test(value) ? undefined : [_i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaPartitioningGroupEventsFormattingMessage', {
    defaultMessage: 'Number of events must be a number'
  })];
}
function validateKafkaTopics(topics) {
  const errors = [];
  topics.forEach((topic, index) => {
    var _topic$when;
    if (!topic.topic || topic.topic === '') {
      errors.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaTopicRequiredMessage', {
          defaultMessage: 'Topic is required'
        }),
        index
      });
    }
    if (!((_topic$when = topic.when) !== null && _topic$when !== void 0 && _topic$when.condition) || topic.when.condition === '' || topic.when.condition.split(':').length - 1 !== 1) {
      errors.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaTopicConditionRequired', {
          defaultMessage: 'Must be a key, value pair i.e. "http.response.code: 200"'
        }),
        index,
        condition: true
      });
    }
  });
  if (errors.length) {
    return errors;
  }
}
function validateKafkaHeaders(pairs) {
  const errors = [];
  const existingKeys = new Set();
  pairs.forEach((pair, index) => {
    const {
      key,
      value
    } = pair;
    const hasKey = !!key;
    const hasValue = !!value;
    if (hasKey && !hasValue) {
      errors.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHeadersMissingKeyError', {
          defaultMessage: 'Missing value for key "{key}"',
          values: {
            key
          }
        }),
        index,
        hasKeyError: false,
        hasValueError: true
      });
    } else if (!hasKey && hasValue) {
      errors.push({
        message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHeadersMissingValueError', {
          defaultMessage: 'Missing key for value "{value}"',
          values: {
            value
          }
        }),
        index,
        hasKeyError: true,
        hasValueError: false
      });
    } else if (hasKey && hasValue) {
      if (existingKeys.has(key)) {
        errors.push({
          message: _i18n.i18n.translate('xpack.fleet.settings.outputForm.kafkaHeadersDuplicateKeyError', {
            defaultMessage: 'Duplicate key "{key}"',
            values: {
              key
            }
          }),
          index,
          hasKeyError: true,
          hasValueError: false
        });
      } else {
        existingKeys.add(key);
      }
    }
  });
  if (errors.length) {
    return errors;
  }
}