import axios from 'axios';
import constants from './constants';
import CRYPTO from 'crypto-js';

export const httpClient = axios.create({
  timeout: 60000,
});

export const getEncryptedText = (data, env) => {
  var truncHexKey = CRYPTO.SHA256(env.toUpperCase() === 'PROD' ? constants.PROD_ENC_KEY : constants.STAG_ENC_KEY)
    .toString()
    .substr(0, 32); // hex encode and truncate

  var key = CRYPTO.enc.Utf8.parse(truncHexKey);

  var iv = CRYPTO.enc.Utf8.parse(env.toUpperCase() === 'PROD' ? constants.PROD_ENC_IV : constants.STAGE_ENC_IV);

  var ciphertext = CRYPTO.AES.encrypt(JSON.stringify(data), key, {
    iv: iv,
    mode: CRYPTO.mode.CBC,
  });

  return ciphertext.toString();
};

export const getDecryptedData = (cipher, env) => {
  var truncHexKey = CRYPTO.SHA256(env.toUpperCase() === 'PROD' ? constants.PROD_ENC_KEY : constants.STAG_ENC_KEY)
    .toString()
    .substr(0, 32); // hex encode and truncate

   

  var key = CRYPTO.enc.Utf8.parse(truncHexKey);

  var iv = CRYPTO.enc.Utf8.parse(env.toUpperCase() === 'PROD' ? constants.PROD_ENC_IV : constants.STAGE_ENC_IV);

  var decryptedData = CRYPTO.AES.decrypt(cipher, key, {
    iv: iv,
    mode: CRYPTO.mode.CBC,
  });



  return decryptedData.toString(CRYPTO.enc.Utf8);
};

export const getWebViewLink = (
  baseUrl,
  token,
  cpsid,
  srcClientId,
  deviceId,
  appVersion,
  deviceVersion,
  userEnv
) => {
  const data = {
    cpsid,
    token,
    srcClientId,
    deviceId,
    appVersion,
    deviceVersion,
    userEnv,
  };

  return httpClient
    .post(`${baseUrl}/partners/v3/generate-magic-link-star-health`, data)
    .then((res) => {
      console.log('getWebViewLink res', { res });
      return res;
    })
    .catch((err) => {
      console.log('getWebViewLink err', { err });
      return err;
    });
};
