/**
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.
*/
/**
 * Helper methods for creating and reporting traces
 */

'use strict';

const crc32 = require('crc-32');

const {
  AsyncStorage,
  KEYS: { REQUEST }
} = require('../core/async-storage');

/**
 * Looks in AsyncStorage context for the request.
 * If it can, checks if the same rule has been reported in request
 * more than 5 times; if it has, returns nothing as it if could not find
 * the request.
 * Improvements: decouple request lookup with throttling rule reports per request
 */
function getRequest(agent, ruleId) {
  const context = AsyncStorage.getContext();
  if (!context || !context[REQUEST]) {
    return;
  }

  const request = context[REQUEST];

  // first time rule is triggered, adding to rules object
  if (!context.rules[ruleId]) {
    context.rules[ruleId] = 0;
  }

  const ruleCount = context.rules[ruleId];
  const { sampling } = agent.config.assess;
  if (sampling && sampling.enable && ruleCount >= sampling.baseline) {
    return;
  }

  context.rules[ruleId]++;
  return request;
}

/**
 * used by rules/sinks to create hashes used for preflight
 *
 * @param {*} digestComponents Array of rule specific things to digest, such as ruleId
 * @return {crc32} Hash of digest
 */
function createHash(digestComponents) {
  let hash = '';
  for (const digest of digestComponents) {
    if (digest) hash = crc32.str(digest, hash);
  }

  return hash;
}

module.exports.getRequest = getRequest;
module.exports.createHash = createHash;
