text: /* eslint-disable camelcase */
  'use strict';
  const tokenUtils = require('../../lib/utils/token-utils');
  const headerUtils = require('../../lib/utils/header-util');
  const businessServiceUtils = require('../utils/business-service-utils');
  
  module.exports = {
    replaceUserToken: function (req, session, serviceTag, cb) {
      session = session || req.session;
      if (session.user.businessServices && serviceTag && session.user.businessServices[serviceTag] && session.user.businessServices[serviceTag].expireDate > Date.now()) {
        cb(null, session.user.businessServices[serviceTag].accessToken);
        return;
      }
      const externalServiceCredentials = serviceTag ? businessServiceUtils.getCredentials(serviceTag, false, req) : req.internalUrl.route.credentials;
      const routerConfig = req ? req.routerConfig : null;
      if (routerConfig && routerConfig.getToken) {
        routerConfig.getToken(req, function (err, accessToken) {
          if (err) {
            return cb(err);
          }
          tokenUtils.exchangeToken(accessToken, headerUtils.getCorrelationId(req), externalServiceCredentials.uaa, cb);
        });
      } else {
        if (!session.user.token){
          return cb('missing user token');
        }
        const jwt = session.user.token.accessToken;
        tokenUtils.exchangeToken(jwt, headerUtils.getCorrelationId(req), externalServiceCredentials.uaa, cb);
      }
    }
  };