"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.handleResponse = exports.getToken = exports.getEncryptedText = exports.getDecryptedData = exports.default = void 0;
var _reactNative = require("react-native");
var _cryptoJs = _interopRequireDefault(require("crypto-js"));
var _reactNativeDeviceInfo = _interopRequireDefault(require("react-native-device-info"));
var _common = require("../helpers/common");
var _constants = _interopRequireDefault(require("../constants"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
// import AsyncStorage from '@react-native-async-storage/async-storage';

// import ASYNC_STORAGE from '../constants/asyncstorage';

const POST = 'post';
const GET = 'get';
const PUT = 'put';
const PATCH = 'patch';
const DELETE = 'delete';
const DEFAULT_ERROR = 'Something went wrong, Please try again later';
let isHandlingSessionExpiration = false;
const SESSION_EXPIRATION_COOLDOWN = 1000; // 1 second cooldown

const getEncryptedText = (data, environment) => {
  var _constants$STAG_ENC_K, _constants$STAGE_ENC_;
  var truncHexKey = _cryptoJs.default.SHA256(environment.toUpperCase() === 'PROD' ? _constants.default.PROD_ENC_KEY : (_constants$STAG_ENC_K = _constants.default.STAG_ENC_KEY) !== null && _constants$STAG_ENC_K !== void 0 ? _constants$STAG_ENC_K : '').toString().substr(0, 32); // hex encode and truncate

  var key = _cryptoJs.default.enc.Utf8.parse(truncHexKey);
  var iv = _cryptoJs.default.enc.Utf8.parse(environment.toUpperCase() === 'PROD' ? _constants.default.PROD_ENC_IV : (_constants$STAGE_ENC_ = _constants.default.STAGE_ENC_IV) !== null && _constants$STAGE_ENC_ !== void 0 ? _constants$STAGE_ENC_ : '');
  var ciphertext = _cryptoJs.default.AES.encrypt(JSON.stringify(data), key, {
    iv: iv,
    mode: _cryptoJs.default.mode.CBC
  });
  return ciphertext.toString();
};
exports.getEncryptedText = getEncryptedText;
const getDecryptedData = (cipher, environment) => {
  var _constants$STAG_ENC_K2, _constants$STAGE_ENC_2;
  var truncHexKey = _cryptoJs.default.SHA256(environment.toUpperCase() === 'PROD' ? _constants.default.PROD_ENC_KEY : (_constants$STAG_ENC_K2 = _constants.default.STAG_ENC_KEY) !== null && _constants$STAG_ENC_K2 !== void 0 ? _constants$STAG_ENC_K2 : '').toString().substr(0, 32); // hex encode and truncate

  var key = _cryptoJs.default.enc.Utf8.parse(truncHexKey);
  var iv = _cryptoJs.default.enc.Utf8.parse(environment.toUpperCase() === 'PROD' ? _constants.default.PROD_ENC_IV : (_constants$STAGE_ENC_2 = _constants.default.STAGE_ENC_IV) !== null && _constants$STAGE_ENC_2 !== void 0 ? _constants$STAGE_ENC_2 : '');
  var decryptedData = _cryptoJs.default.AES.decrypt(cipher, key, {
    iv: iv,
    mode: _cryptoJs.default.mode.CBC
  });
  return decryptedData.toString(_cryptoJs.default.enc.Utf8);
};
exports.getDecryptedData = getDecryptedData;
const getToken = async () => {
  // try {
  //   const token = await AsyncStorage.getItem(ASYNC_STORAGE?.ACCESS_TOKEN);
  //   if (token !== null) {
  //     // token previously stored
  //     return token;
  //   }
  // } catch (e) {
  //   throw new Error('Token not found or could not be retrieved');
  // }
};
exports.getToken = getToken;
const handleResponse = async (response, isEncrypted, environment) => {
  const contentType = response.headers.get('Content-Type');
  if (contentType) {
    let resp = null;
    if (contentType.indexOf('application/json') !== -1) {
      resp = await response.json();
    } else if (contentType && contentType.indexOf('text/html') !== -1) {
      resp = await response.text();
    }
    if (!isEncrypted) return resp;
    const parsed = await JSON.parse(getDecryptedData(resp, environment));
    // const {Auth} = Store.getState();

    if (Number(parsed === null || parsed === void 0 ? void 0 : parsed.code) == 1) {
      return parsed;
    } else if ((parsed === null || parsed === void 0 ? void 0 : parsed.code) == -1) {
      _reactNative.DeviceEventEmitter.emit('session_expired');
      return parsed;
    } else {
      return parsed;
    }
  } else {
    return response.text();
  }
};
exports.handleResponse = handleResponse;
const request = async (route, {
  baseURL = _constants.default.STAGE_BASE_URL,
  environment = 'uat',
  method = GET,
  payload = null,
  formData = null,
  headers = {},
  json = true,
  priv = true,
  isEncrypted = true,
  content_type = null,
  isVisitEncrypted = false
}) => {
  baseURL = environment.toUpperCase() === 'PROD' ? _constants.default.PROD_BASE_URL : _constants.default.STAGE_BASE_URL;
  const activeVersion = _reactNativeDeviceInfo.default.getVersion(); // return "0.0.2"
  const activeBuildNumber = _reactNativeDeviceInfo.default.getBuildNumber(); // return 2
  const appVersion = `${_reactNative.Platform.OS} ${activeVersion}-${activeBuildNumber}`;
  console.log("baseee urlss", baseURL);
  let init = {
    method: method,
    headers: {
      'api-key': environment.toUpperCase() === 'PROD' ? _constants.default.PROD_API_KEY : _constants.default.STAGE_API_KEY,
      userFrom: 'GoodFlip',
      // This has to be set to "PSP" incase of user is from PSP. This will be sent from register API.
      source: 'GoodFlip',
      appVersion: appVersion,
      platform: 'app',
      ...headers
    },
    body: ''
  };

  //   const {Auth} = Store.getState();

  if (formData) {
    init = {
      ...init,
      headers: {
        ...init.headers,
        'content-type': 'multipart/form-data'
      },
      body: formData
    };
  }
  if (payload) {
    init = {
      ...init,
      headers: {
        ...init.headers
      },
      body: getEncryptedText(payload, environment)
    };
  }
  if (content_type) init.headers['Content-Type'] = content_type;

  //   if (priv && Auth.user.data?.token) {
  //     init.headers = {
  //       ...init.headers,
  //       token: Auth.user.data?.token,
  //     };
  //   }

  return fetch(`${baseURL}${route}`, init).then(async res => {
    if (res.status === 401) {
      handleSessionExpired();
      throw new Error('Unauthorized');
    }
    if (!json) {
      return res;
    }
    res = await handleResponse(res, isVisitEncrypted ? false : isEncrypted, environment);
    return res;
  }).catch(async error => {
    // Remove decryption attempt on error as it may not be encrypted
    if (error.message === 'Unauthorized') {
      // Reject the promise for 401 errors
      throw error;
    }
    throw error; // Re-throw other errors to be handled by the caller
  });
};
const handleError = (error, msg = DEFAULT_ERROR) => {
  let errMsg = msg;

  // exception string error
  if (typeof msg === 'string') {
    _reactNative.Alert.alert('Alert', (0, _common.checkStringTypeOf)(msg));
    return {
      status: (error === null || error === void 0 ? void 0 : error.status) || 500,
      message: errMsg
    };
  }
  switch (error === null || error === void 0 ? void 0 : error.status) {
    default:
      errMsg = DEFAULT_ERROR;
  }
  _reactNative.Alert.alert('Alert', JSON.stringify(errMsg));
  return {
    status: error === null || error === void 0 ? void 0 : error.status,
    message: errMsg
  };
};
const handleSessionExpired = () => {
  if (isHandlingSessionExpiration) {
    return {
      code: -1,
      message: 'Session expired'
    };
  }
  isHandlingSessionExpiration = true;

  // Use setTimeout to ensure state updates complete before navigation
  setTimeout(() => {
    _reactNative.DeviceEventEmitter.emit('session_expired');
  }, 0);

  // Reset the flag after cooldown period
  setTimeout(() => {
    isHandlingSessionExpiration = false;
  }, SESSION_EXPIRATION_COOLDOWN);
  return {
    code: -1,
    message: 'Session expired'
  };
};
var _default = exports.default = {
  POST,
  PUT,
  PATCH,
  GET,
  DELETE,
  request,
  handleResponse,
  handleError,
  getToken
};
//# sourceMappingURL=base.js.map