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

/**
 * Wraps binary expressions in one of the following: `ContrastMethods.__add`,
 * `ContrastMethods.__doubleEqual`, `ContrastMethods.__notDoubleEqual`,
 * `ContrastMethods.__tripleEqual`, `ContrastMethods.__notTripleEqual`.
 * ```
 * foo !== 'bar'
 * // becomes:
 * ContrastMethods.__notTripleEquals(foo, 'bar')
 * ```
 * @param {import('@babel/traverse').NodePath<import('@babel/types').BinaryExpression>} path
 * @param {import('.').State} state
 */
module.exports = function BinaryExpression(path, state) {
  const spec = state.specs.find(({ token }) => token === path.node.operator);
  if (
    !spec ||
    !state.callees[spec.name] ||
    (path.node.operator === '+' &&
      t.isLiteral(path.node.left) &&
      t.isLiteral(path.node.right))
  )
    return;

  state.rewriteLog.logRewrite(spec.name);
  path.replaceWith(
    t.callExpression(state.callees[spec.name], [
      path.node.left,
      path.node.right
    ])
  );
};

/**
 * @param {babel.NodePath<babel.types.CallExpression>} path AST path
 * @param {import('./callees').Spec} spec
 */
module.exports.unwrite = function unwriteBinaryExpression(path, spec) {
  path.replaceWith(
    t.binaryExpression(
      spec.token,
      path.node.arguments[0],
      path.node.arguments[1]
    )
  );
};
