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

let rewriter;
const logger = require('../../core/logger')(
  'contrast:rules:propagation:handlebars'
);

/**
 * Setup rewriter state
 * @param   {Object}   agent agent instance
 */
module.exports.setup = function(agent) {
  rewriter = require('../../core/rewrite')(agent);
};

function getFunctionBody(fn) {
  // strip contrast rewrite header because it looks like a function.
  // this is the global injection stuff
  // NOTE: this creates two shallow copies.
  fn = fn
    .split('\n')
    .slice(4)
    .join('\n');

  return fn.slice(fn.indexOf('{') + 1, fn.lastIndexOf('}'));
}

/**
 * param logic taken from handlebars/compiler/javascript-compiler.js:l249
 * used for generating function signture
 * @param   {Object}   obj this object for caller
 * @returns {string[]}     list of params in the signature
 */
function getParams(obj) {
  const params = ['container', 'depth0', 'helpers', 'partials', 'data'];

  if (obj.useBlockParams || obj.useDepths) {
    params.push('blockParams');
  }
  if (obj.useDepths) {
    params.push('depths');
  }

  return params;
}

function handle(data) {
  try {
    let source = data.result.main.toString();
    source = rewriter.rewriteCode(source, '', false, false).code;

    source = getFunctionBody(source);

    const params = getParams(data.obj);

    data.result.main = Function(...params, source);
  } catch (e) {
    logger.warn(`Failed to rewrite handlebars template. ${e}`);
  }
}

module.exports.getFunctionBody = getFunctionBody;
module.exports.getParams = getParams;
module.exports.handle = handle;
