/**
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 logger = require('../../core/logger')('contrast:rules:exclusions');
const UrlExclusion = require('./url');
const InputExclusion = require('./input');
const { EXCLUSION_TYPES } = require('../../constants');

class ExclusionFactory {
  constructor({ featureSet, assess, protect }) {
    this.assess = assess;
    this.protect = protect;
    const settings = {
      ...featureSet.serverFeatures,
      ...featureSet.applicationSettings
    };
    this.updateSettings({
      settings,
      assess,
      protect
    });
  }

  /**
   * Updates assess/protect flags and
   * builds new input/url exclusions based on
   * setting updates
   * @param {Object} params
   * @param {Object} params.settings
   * @param {Boolean} params.assess flag to say whether assess is enabled
   * @param {Boolean} params.protect flag to say whether protect is enabled
   */
  updateSettings({ settings, assess, protect }) {
    // ServerFeatures will have enabled/disabled settings.
    this.setModes({ assess, protect });

    if (!settings || !Object.keys(settings).length) {
      return;
    }

    logger.info('exclusions updated.');
    this.inputExclusions = this.buildExclusions(
      EXCLUSION_TYPES.INPUT,
      InputExclusion,
      settings.exclusionsList
    );
    this.urlExclusions = this.buildExclusions(
      EXCLUSION_TYPES.URL,
      UrlExclusion,
      settings.exclusionsList
    );
  }

  /**
   * Sets the active modes of the factory from serverFeatures.
   * @param {Object} params
   * @param {Boolean} params.assess flag to say whether assess is enabled
   * @param {Boolean} params.protect flag to say whether protect is enabled
   */
  setModes({ assess, protect }) {
    const assessEnabled = assess;
    const protectEnabled = protect;

    if (assessEnabled !== undefined) {
      this.assess = assessEnabled;
    }

    if (protectEnabled !== undefined) {
      this.protect = protectEnabled;
    }
  }

  buildExclusions(type, Ctor, list = []) {
    const dtms = list.filter(
      (e) =>
        e.type === type &&
        ((e.assess && this.assess) || (e.protect && this.protect))
    );
    return safeCreateExclusions(Ctor, dtms);
  }

  getUrlExclusions(mode = 'defend') {
    return filterByMode(mode, this.urlExclusions);
  }

  getInputExclusions(mode = 'defend') {
    return filterByMode(mode, this.inputExclusions);
  }
}

function safeCreateExclusions(Exclusion, dtms = []) {
  const exclusions = [];
  dtms.forEach((dtm) => {
    try {
      const ex = new Exclusion(dtm);
      exclusions.push(ex);
    } catch (e) {
      logger.error(e.message);
    }
  });

  return exclusions;
}

function filterByMode(mode, exclusions = []) {
  return exclusions.filter((e) => e[mode]);
}

module.exports = ExclusionFactory;
module.exports.filterByMode = filterByMode;
module.exports.safeCreateExclusions = safeCreateExclusions;
