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

const common = require('../../../protect/rules/common');
const { ATTACK_STATUS } = common;

/**
 * Sample
 */
class Sample {
  /**
   * @param {UserInput} input
   * @param {ApplicationContext} appContext
   * @param {Object} [assessment] Result of rule evaluation
   */
  constructor(input, appContext, assessment) {
    if (appContext && appContext.setStack) {
      appContext.setStack();
    }
    this.appContexts = [appContext];
    this.confirmedAttack = false;
    this.effective = false;
    this.blocked = false;
    this.filters = [];
    this.details = null;
    this.input = input;
    this.request = appContext.request;

    // extra info for processing at sink time.
    // NOT TO BE INCLUDED IN ACTUAL DTM AT REPORTING TIME.
    // This is particularly useful when using the agent lib for processing
    // mongo expansion and injection.
    this._inputInfoForSink = {};

    this.assessment = assessment;

    if (assessment) {
      if (assessment.results && assessment.results.importance === 'DEFINITE') {
        this.confirmedAttack = true;
      }

      if (assessment.patterns) this.filters.push(...assessment.patterns.ids);
      if (assessment.keywords) this.filters.push(...assessment.keywords.ids);
      if (assessment.searchers) this.filters.push(...assessment.searchers.ids);
    }

    this.timestamp = {
      start: Date.now(),
      // FIX ********************
      elapsed: 5000 // **********
    };
  }

  /**
   * Returns the status of the sample based on whether the input
   * was effective ( attack vs probe ), and whether it was blocked.
   * Values: ineffective, blocked_at_perimeter, blocked, exploited.
   * @returns {String}
   */
  getStatus() {
    if (this.blocked) {
      return this.effective
        ? ATTACK_STATUS.BLOCKED
        : ATTACK_STATUS.BLOCKED_AT_PERIMETER;
    } else {
      return this.effective
        ? ATTACK_STATUS.EXPLOITED
        : ATTACK_STATUS.INEFFECTIVE;
    }
  }

  /**
   * Appends an ApplicationContext (or list of) to the sample's set.
   * @param {AppplicationContext} appContext Context(s)
   */
  captureAppContext(appContext) {
    if (appContext && appContext.setStack) {
      appContext.setStack(); // NODE-550: sink events lacked stack
    }
    this.appContexts = [].concat(this.appContexts, appContext);
  }

  toSerializable() {
    const appContext = extractAppContext(this);
    const stack = (appContext.stack || []).map((item) => ({
      declaringClass: item.type || '',
      fileName: item.file,
      lineNumber: item.lineNumber,
      methodName: item.method || '<anonymous>'
    }));

    const data = {
      timestamp: this.timestamp,
      request: this.request ? this.request.toSerializable() : {},
      details: this.details,
      stack,
      blocked: this.blocked,
      input: this.input
        ? {
            ...this.input.toSerializable(),
            applicable: this.applicable,
            confirmedAttack: this.confirmedAttack,
            effective: this.effective,
            filters: this.filters
          }
        : null
    };

    return data;
  }
}

/**
 * Extract the appropriate context from the sample to use for reporting.
 * Samples that are effective should have captured additional ApplicationContext
 * during sink evaluations - get the latter of these for effective attacks.
 * @param {Sample} sample
 * @returns {ApplicationContext}
 */
function extractAppContext(sample) {
  return !sample.effective || sample.appContexts.length === 1
    ? sample.appContexts[0]
    : sample.appContexts[1];
}

module.exports = Sample;
