/**
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';

/**
 * An input is a generic complicated input if it has a length of 10 or more characters and meets
 * one of the following criteria: 1. Contains a slash+star followed somewhere by a star+slash 2.
 * Contains one or more whitespace characters and two or more suspicious characters
 *
 * ported from the original Java implementation in SQLRaspRule.java
 * @param  {String} input potentially sql input
 * @return {Boolean}      is generic complicated?
 */
module.exports = function isGenericComplicated(input) {
  if (!input || input.length < 10) return false;

  // if there's a sql comment, it is generic complicated.
  if (/\/\*.*\*\//.test(input)) return true;

  const numSuspiciousChars = countCharOccurences(input, /["'`;\-%,()|-]/g);
  const numOfWhitespaceChars = countCharOccurences(input, /[ \t\n]/);

  return numSuspiciousChars >= 2 && numOfWhitespaceChars >= 1;
};

/**
 * count the number of substrings in a given string using a regular expression
 * intended to be used with character groups and not long strings.
 * @param   {String} str   input string
 * @param   {Regex}  regex the substring to be counted (intended to be a character group)
 * @returns {Number}       count of substring
 */
function countCharOccurences(str, regex) {
  return (str.match(regex) || []).length;
}

module.exports.countCharOccurences = countCharOccurences;
module.exports.ID = 'COMPLICATED-1';
