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

const Address = require('./address');
const { objToMap } = require('../../helpers');

const objToKeyPair = (obj = {}) =>
  Object.keys(obj).map((key) => [key, [key, obj[key]]]);

const resolveUri = (uri, queryString) =>
  queryString ? `${uri}?${queryString}` : uri;

module.exports = function HttpRequest(request = {}) {
  // We actually prefer these values pre-toSerializable()
  const { headers = {} } = request;

  if (request.toSerializable) {
    request = request.toSerializable();
  }

  const address = Address(request.ip, headers.host, request.port);

  return new dtm.HttpRequest({
    2: address.array, //                                   3                    sender
    4: request.protocol, //                                5                  protocol
    5: request.version, //                                 6                   version
    6: request.method, //                                  7                    method
    7: resolveUri(request.uri, request.queryString), //    8                       raw
    15: objToKeyPair(request.parameters), //              16 normalized_request_params
    19: objToMap(headers), //                             20           request_headers
    29: request.body, //                                  30       parsed_request_body
    30: !!request.body, //                                33       request_body_binary
    49: request.serverVersionInfo //                      50                  metadata
  });
};
