/**
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 {
  VIRTUAL_PATCH_INPUT_TYPES,
  VIRTUAL_PATCH_EVALUATIONS
} = require('../../enums');
const { wrapToObject } = require('../../helpers');

function VirtualPatch({ name, key, headers, parameters, urls, uuid } = {}) {
  const conditions = { headers, parameters, urls };

  return wrapToObject(
    new settings.VirtualPatch([
      name, //                                                      1       name
      uuid, //                                                      2       uuid
      key, //                                                       3        key
      undefined, //                                                 4          -
      undefined, //                                                 5          -
      undefined, //                                                 6          -
      VirtualPatchConditions(conditions).map((vpc) => vpc.array) // 7 conditions
    ]),
    (vp) => {
      vp.conditionsList.forEach((condition) => {
        condition.inputType = VIRTUAL_PATCH_INPUT_TYPES[condition.inputType];
        condition.evaluation = VIRTUAL_PATCH_EVALUATIONS[condition.evaluation];
      });
    }
  );
}

function VirtualPatchCondition({ name, value, input, evaluation }) {
  return wrapToObject(
    new settings.VirtualPatchCondition([
      undefined, //                            1          -
      name, //                                 2       name
      value, //                                3      value
      VIRTUAL_PATCH_INPUT_TYPES[input], //     4 input_type
      VIRTUAL_PATCH_EVALUATIONS[evaluation] // 5 evaluation
    ]),
    (condition) => {
      condition.inputType = VIRTUAL_PATCH_INPUT_TYPES[condition.inputType];
      condition.evaluation = VIRTUAL_PATCH_EVALUATIONS[condition.evaluation];
    }
  );
}

function VirtualPatchConditions({ headers, parameters, urls }) {
  return [headers, parameters, urls].reduce(
    (acc, list = []) =>
      list.reduce((acc, condition) => {
        acc.push(VirtualPatchCondition(condition));
        return acc;
      }, acc),
    []
  );
}

module.exports = {
  VirtualPatch,
  VirtualPatchCondition
};
