/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

/**
 * @typedef {Object} Condition
 * @property {string=} name
 * @property {string=} value
 * @property {string} evaluation
 */

/**
 * @typedef {Object} Input
 * @property {string=} name
 * @property {string} value
 */

/**
 * Evaluator factories take a "value" and return an Evaluator function.
 * @type {{ [strategy: string]: (value: string) => (input: string) => boolean}}
 */
const EVALUATORS = {
  contains: (value) => (input) => input.indexOf(value) >= 0,
  doesnt_contain: (value) => (input) => input.indexOf(value) < 0,
  equals: (value) => (input) => value.toString() === input.toString(),
  doesnt_equal: (value) => (input) => value.toString() !== input.toString(),
  matches: (value) => (input) => new RegExp(value, 'i').test(input),
  doesnt_match: (value) => (input) => !new RegExp(value, 'i').test(input)
};

/**
 * Given a condition, will return a function that will evaluate an
 * input string as described by the condition. The returned function
 * will return the condition itself if the evaluation is met, otherwise it will
 * return `null`.
 * @param {Condition} condition The condition to use to do evaluation
 * @returns {(input: Input) => Condition | null}
 */
module.exports.create = function createUserInputEvaluator(condition) {
  const name = (condition.name || '').toLowerCase();
  const value = (condition.value || '').toLowerCase();
  const strategy = condition.evaluation.toLowerCase();

  if (!EVALUATORS[strategy]) return () => null;

  const evaluator = EVALUATORS[strategy](value);

  return (input) => {
    if (!input || (input.name || '').toLowerCase() !== name) return null;
    return evaluator(input.value) ? condition : null;
  };
};
