/**
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 { settings } = require('@contrast/protobuf-api');

const Exclusions = require('./exclusions');
const ProtectionRule = require('./protection-rule');
const Reaction = require('./reaction');
const { VirtualPatch } = require('./virtual-patch');
const {
  EXCLUSION_TYPES,
  EXCLUSION_INPUT_TYPES,
  EXCLUSION_MATCH_STRATEGIES,
  PROTECTION_RULE_MODES,
  VIRTUAL_PATCH_EVALUATIONS,
  VIRTUAL_PATCH_INPUT_TYPES
} = require('../../enums');
const { wrapToObject } = require('../../helpers');

function ApplicationSettings({
  defend: { virtualPatches = [], protectionRules = [] } = {},
  exceptions = {},
  assessment = {},
  reactions = []
} = {}) {
  return wrapToObject(
    new settings.ApplicationSettings([
      undefined, //                                               1                     -
      virtualPatches.map(VirtualPatch).map((vp) => vp.array), //  2       virtual_patches
      protectionRules.map(ProtectionRule).map((r) => r.array), // 3      protection_rules
      undefined, //                                               4                     -
      Exclusions(exceptions).map((m) => m.array), //              5            exclusions
      assessment.disabledRules, //                                6 disabled_assess_rules
      reactions.map(Reaction).map((r) => r.array), //             7             reactions
      assessment.session_id //                                    8            session_id
    ]),
    ApplicationSettings.toObject
  );
}

ApplicationSettings.toObject = ({
  exclusionsList,
  protectionRulesList,
  virtualPatchesList
}) => {
  protectionRulesList.forEach((rule) => {
    rule.mode = PROTECTION_RULE_MODES[rule.mode];
  });
  virtualPatchesList.forEach((rule) => {
    rule.conditionsList.forEach((cond) => {
      cond.inputType = VIRTUAL_PATCH_INPUT_TYPES[cond.inputType];
      cond.evaluation = VIRTUAL_PATCH_EVALUATIONS[cond.evaluation];
    });
  });
  exclusionsList.forEach((exclusion) => {
    exclusion.type = EXCLUSION_TYPES[exclusion.type];
    exclusion.matchStrategy =
      EXCLUSION_MATCH_STRATEGIES[exclusion.matchStrategy];
    exclusion.inputType = EXCLUSION_INPUT_TYPES[exclusion.inputType];
  });
};

module.exports = ApplicationSettings;
