/**
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 t = require('@babel/types');
const isContrastMethod = require('./is-contrast-method');

const SKIP = Symbol('SKIP');
module.exports.SKIP = SKIP;

/**
 * Rewrites template literals to `ContrastMethods.__contrastTag` tagged template
 * expressions.
 * ```
 * const str = `hello ${name}`;
 * // becomes
 * const str = ContrastMethods.__contrastTag`hello ${name}`;
 * ```
 * @param {import('@babel/traverse').NodePath<import('@babel/types').TemplateLiteral>} path
 * @param {import('.').State} state
 */
module.exports = function TemplateLiteral(path, state) {
  if (!state.callees.__contrastTag || path.node[SKIP]) return;

  state.rewriteLog.logRewrite('__contrastTag');
  const taggedTemplateExpression = t.taggedTemplateExpression(
    state.callees.__contrastTag,
    path.node
  );
  // Prevents an error where the new taggedTemplateExpression quasi is traversed again.
  taggedTemplateExpression.quasi[SKIP] = true;
  path.replaceWith(taggedTemplateExpression);
};

/**
 * We want to avoid rewriting the template literals in the quasi of a template expression because, in theory,
 * all propagation we need will be handled inside the function, which we're already rewriting.
 * So, we add a SKIP property to the quasi. When the leave pass of traversal runs, TemplateLiterals will
 * check for SKIP to know that they are the children of a TaggedTemplateExpression.
 * @param {import('@babel/traverse').NodePath<import('@babel/types').TaggedTemplateExpression>} path
 */
module.exports.skip = function skipTemplateLiteral(path) {
  path.node.quasi[SKIP] = true;
};

/**
 * @param {import('@babel/traverse').NodePath<import('@babel/types').TaggedTemplateExpression>} path
 */
module.exports.unwrite = function unwriteTemplateLiteral(path) {
  if (!isContrastMethod(path.node.tag)) return;
  path.replaceWith(path.node.quasi);
};
