/**
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 non-literal discriminants and case tests in `ContrastMethods.__cast`.
 * ```
 * switch(key) {
 *  case obj[dynamic]:
 *    // do stuff
 *  case dynamic:
 *    // do stuff
 *  case 'literal':
 *    // do stuff
 * }
 * // becomes:
 * switch(ContrastMethods.__cast(key)) {
 *  case ContrastMethods.__cast(obj[dynamic]):
 *    // do stuff
 *  case ContrastMethods.__cast(dynamic):
 *    // do stuff
 *  case 'literal':
 *   // do stuff
 * }
 * ```
 * @param {import('@babel/traverse').NodePath<import('@babel/types').SwitchStatement>} path
 * @param {import('.').State} state
 */
module.exports = function SwitchStatement(path, state) {
  if (!state.callees.__cast) return;
  let rewritten = false;

  if (!t.isLiteral(path.node.discriminant)) {
    rewritten = true;
    path.node.discriminant = t.callExpression(state.callees.__cast, [
      path.node.discriminant
    ]);
  }

  path.node.cases = path.node.cases.map((c) => {
    if (!c.test || t.isLiteral(c.test)) return c;

    rewritten = true;
    c.test = t.callExpression(state.callees.__cast, [c.test]);
    return c;
  });

  if (!rewritten) return;
  state.rewriteLog.logRewrite('__cast');
};

/**
 * @param {import('@babel/traverse').NodePath<import('@babel/types').CallExpression>} path
 */
module.exports.unwrite = function unwriteSwitchStatement(path) {
  path.replaceWith(path.node.arguments[0]);
};
