var express = require('express');
var router = express.Router();
var template = require('./../parts/mgmt/templates');
var users = require('./../parts/mgmt/users');
var apps = require('./../parts/mgmt/apps');
var campaigns = require('./../parts/mgmt/campaigns');
var netcoreEmail = require('./../parts/mgmt/netcore-email');
var funnels = require('./../parts/mgmt/funnels');
var transaction_camp = require('./../parts/mgmt/transaction-camp');
var metrices = require('./../parts/mgmt/metrices');
var devents = require('./../parts/data/events'),
    ErrorMsg = require('./../constants/constants'),
    url = require('url'),
    cacheApi = require('./../utils/semusi.cache.js'),
    common = require('./../utils/common.js');
const tenMinutesInSec = 600;
const logger = require('../../logger');
var djourneys = require('./../parts/data/journey');
var cookieParser = require('cookie-parser')
var csrf = require('../../frontend/express/csrf');
var csrfProtection = csrf({
    cookie: {
        httpOnly: true,     // Ensures the CSRF cookie is not accessible via JavaScript
        secure: true,       // Ensures the CSRF cookie is only sent over HTTPS
        sameSite: 'Lax'     // Controls whether the CSRF cookie is sent with cross-site requests
    }
});
var push = require('./../parts/mgmt/push');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.send('Call from home route' );
});
router.get('/o/metrices/token', csrfProtection , function (req, res, next) {
    let token = req.csrfToken();
    cacheApi.setKeywithTTL(token, "true", 5000); 
    res.send({token:token});
}); 
// template route start from here 
router.post('/i/templates/create', csrfProtection ,function (req, res) {
    validateUserForWriteAPI(template.createTemplate, req, res);
});
router.post('/i/templates/getIEmailEditor', csrfProtection ,function (req, res) {
    validateUserForWriteAPI(template.getIEmailEditor, req, res);
});
router.post('/i/templates/update', csrfProtection ,function (req, res) {
    validateUserForWriteAPI(template.updateTemplate, req, res);
});
router.post('/i/templates/delete', function (req, res) {
    validateUserForWriteAPI(template.deleteTemplate, req, res);
});
router.post('/i/templates/response', function (req, res) {
    validateUserForWriteAPI(template.updateResponse, req, res);
});
router.post('/i/templates/createCampaign',csrfProtection ,function (req, res) {
    validateUserForWriteAPI(template.createCampaign, req, res);
});
router.get('/i/templates/updateCampaign', function (req, res) {
    validateUserForWriteAPI(template.updateCampaign, req, res);
});
router.get('/i/templates/validateTemplateName', function (req, res) {
    validateUserForDataReadAPI(req,res,template.validateTemplateName);
});
router.get('/i/templates/setActiveCampaign', function (req, res) {
    validateUserForDataReadAPI(req,res, template.setActiveCampaign);
});
router.post('/i/templates/getTemplateMetaData', function (req, res) {
    validateUserForWriteAPI(template.getTemplateMetaData, req, res);
});
router.post('/i/templates/saveVariant', function (req, res) {
    validateUserForWriteAPI(template.saveVariant, req, res);
});
router.get('/i/templates/deleteCampaign', function (req, res) {
    validateUserForWriteAPI(template.deleteCampaign, req, res);
});
router.get('/i/templates/deleteTemplate', function (req, res) {
    validateUserForWriteAPI(template.deleteTemplate, req, res);
});
router.get('/i/templates/copyCampaign', function (req, res) {
    validateUserForDataReadAPI(req,res, template.copyCampaign);
});

router.post('/i/templates/getTransitionalCampaigns', function (req, res) {
    validateUserForWriteAPI(template.getTransitionalCampaigns, req, res);
});
router.post('/i/templates/getCampaignDetails', function (req, res) {
    validateUserForWriteAPI(template.getCampaignDetails, req, res);
});
router.post('/i/templates/downloadTransitionalCampaigns', function (req, res) {
    validateUserForWriteAPI(template.downloadTransitionalCampaigns, req, res);
});
router.post('/i/templates/saveVarient', function (req, res) {
    validateUserForWriteAPI(template.saveVarient, req, res);
});

router.get('/o/templates/getAllTemplates', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getAllReferals);
});
router.get('/o/templates/getTemplatesById', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getTemplatesById);
});
router.get('/o/templates/getTemplatesByType', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getTemplatesByType);
});
router.get('/o/templates/getAllAppTemplates', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getAllAppTemplates);
});
router.get('/o/templates/getShortUrls', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getShortUrls);
});

router.get('/o/templates/getCampaigns', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getCampaigns);
});
router.get('/o/templates/getActiveCampaigns', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveCampaigns);
});
router.get('/o/templates/getCampaignsByStatus', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getCampaignsByStatus);
});
router.get('/o/templates/initiateCampaignExports', function (req, res) {
    validateUserForDataReadAPI(req, res, template.initiateCampaignExports);
});
router.get('/o/templates/getCampaignById', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getCampaignById);
});
router.get('/o/templates/getPastAndActiveCampaigns', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getPastAndActiveCampaigns);
});
router.get('/o/templates/getCampaignFeedbackById', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getCampaignFeedbackById);
});
router.get('/o/templates/getCampaignReachById', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getCampaignReachById);
});

router.get('/o/templates/getAtRiskAudienceSegmentId', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getAtRiskAudienceSegmentId);
});
router.get('/o/templates/getCustomData', function (req, res) {
    validateUserForDataReadAPI(req, res, template.getCustomData);
});
router.get('/o/templates/downloadActiveCampaignData', function(req,res){
    validateUserForDataReadAPI(req,res,template.downloadCampaignDataCommon)    
});
router.get('/o/templates/getRequestId', function(req,res){
    validateUserForDataReadAPI(req,res,template.getRequestId)
});
router.get('/o/templates/getCampaignStatsDateWise',function(req,res){
    validateUserForDataReadAPI(req,res,template.getCampaignStatsDateWise)
});
router.get('/o/templates/downloadCampaignDataById',function(req,res){
    validateUserForDataReadAPI(req,res,template.downloadCampaignDataCommon)
});
router.get('/o/templates/downloadTransactionalCampaignData', function(req,res){
    validateUserForDataReadAPI(req,res,template.downloadCampaignDataCommon)    
});
// users route start from here 
router.post('/i/users/create', function (req, res) {
    validateUserForSignUp(users.createUser, req, res);
});
router.post('/i/users/update',csrfProtection, function (req, res) {
    validateUserForWriteAPI(users.updateUser, req, res);
});
router.post('/i/users/delete', function (req, res) {
    validateUserForWriteAPI(users.delete, req, res);
});
router.post('/i/users/recover', function (req, res) {
    validateUserForWriteAPI(users.recover, req, res);
});
router.get('/i/users/updateApproved', function (req, res) {
    validateUserForDataReadAPI(req, res , users.updateApprovedUser);
});
// apps route end from here 
router.get('/i/apps/getAppAuthState', function(req, res){
    validateUserForDataReadAPI( req, res, apps.getAppAuthState)
});
router.post('/i/apps/addAppToGroup',csrfProtection, function(req, res){
    validateUserForWriteAPI(apps.addAppToGroup, req, res)
});
router.post('/i/apps/updateAppToGroup',csrfProtection ,function(req, res){
    validateUserForWriteAPI(apps.updateAppToGroup, req, res)
});
router.get('/i/apps/getAppStoreInfo', function (req, res) {
    validateUserForWriteAPI(apps.getAppStoreInfo, req, res);
});
router.get('/i/apps/getCurrentAppKeys', function (req, res) {
    validateUserForDataReadAPI(req,res, apps.getCurrentAppKeys);
});
router.get('/i/apps/SendDevData', function (req, res) {
    validateUserForWriteAPI(apps.SendDevData, req, res);
});
router.get('/i/apps/processfile', function (req, res) {
    validateUserForWriteAPI(apps.processfile, req, res);
});
router.get('/i/apps/processUninstallData', function (req, res) {
    validateUserForWriteAPI(apps.processUninstallData, req, res);
});
router.get('/i/apps/checkemaildomain', function (req, res) {
    validateUserForWriteAPI(apps.checkemaildomain, req, res);
});
router.post('/i/apps/updateApp',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.updateApp, req, res);
});
// Api for custom feilds and Custom code from settings
router.post('/i/apps/save_custom',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.save_custom, req, res);
});
router.post('/i/apps/deleteCallBackUrl', csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.deleteCallBackUrl, req, res);
});
router.get('/i/apps/create', function (req, res) {
    validateUserForWriteAPI(apps.createApp, req, res);
});
router.get('/i/apps/createChatBot', function (req, res) {
    validateUserForWriteAPI(apps.createChatBot, req, res);
});
router.get('/i/apps/update', function (req, res) {
    validateUserForWriteAPI(apps.update, req, res);
});
router.get('/i/apps/delete', function (req, res) {
    validateUserForWriteAPI(apps.deleteApp, req, res);
});
router.get('/i/apps/reset', function (req, res) {
    validateUserForWriteAPI(apps.reset, req, res);
});
router.post('/i/apps/updateGCMKeys',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.updateGCMKeys, req, res);
});
router.get('/i/apps/updateAppiceKeys', function (req, res) {
    validateUserForWriteAPI(apps.updateAppiceKeys, req, res);
});
router.post('/i/apps/updateIOSCertificates',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.updateIOSCertificates, req, res);
});
router.post('/i/apps/saveAppAuthState',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveAppAuthState, req, res);
});
router.post('/i/apps/saveEmailBudget',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveEmailBudget, req, res);
});
router.post('/i/apps/saveCmpSetting',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveCmpSetting, req, res);
});
router.post('/i/apps/savekillSwitchSetting', csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.savekillSwitchSetting, req, res);
});
//router.get('/i/apps/saveOtpDetails', apps.saveOtpDetails);
router.get('/i/apps/updateDeviceMetaData', function (req, res) {
    validateUserForWriteAPI(apps.updateDeviceMetaData, req, res);
});
router.get('/i/apps/setAppMode', function (req, res) {
    validateUserForDataReadAPI(req,res,apps.setAppMode);
});
router.get('/i/apps/setFcmMode', function (req, res) {
    validateUserForDataReadAPI(req,res,apps.setFcmMode);
});
router.get('/i/apps/saveModule', function (req, res) {
    validateUserForWriteAPI(apps.saveModule, req, res);
});
router.get('/i/apps/saveAppModules', function (req, res) {
    validateUserForWriteAPI(apps.saveAppModules, req, res);
});
router.get('/i/apps/updateModule', function (req, res) {
    validateUserForWriteAPI(apps.updateModule, req, res);
});
router.get('/i/apps/deleteModule', function (req, res) {
    validateUserForWriteAPI(apps.deleteModule, req, res);
});
router.post('/i/apps/saveOtherAppGroup',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.saveOtherAppGroup, req, res);
});
router.post('/i/apps/updateOtherAppGroup',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.updateOtherAppGroup, req, res);
});
router.get('/i/apps/deleteAppFromGroup', function (req, res) {
    validateUserForWriteAPI(apps.deleteAppFromGroup, req, res);
});
router.get('/i/apps/deleteOtherAppGroup', function(req, res){
    validateUserForWriteAPI(apps.deleteOtherAppGroup, req, res);
});
router.get('/i/apps/getAppsAverageSession', function (req, res) {
    validateUserForDataReadAPI( req, res,apps.getAppsAverageSession);
});
router.get('/i/apps/saveChildApp', function (req, res) {
    validateUserForWriteAPI(apps.saveChildApp, req, res);
});
router.get('/i/apps/updateChildApp', function (req, res) {
    validateUserForWriteAPI(apps.updateChildApp, req, res);
});
router.get('/i/apps/deleteChildApp', function (req, res) {
    validateUserForWriteAPI(apps.deleteChildApp, req, res);
});
router.get('/i/apps/updateLinkingField', function (req, res) {
    validateUserForWriteAPI(apps.updateLinkingField, req, res);
});
router.post('/i/apps/saveEmailConfiguration',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.saveEmailConfiguration, req, res);
});
router.post('/i/apps/saveSMSConfiguration',csrfProtection, function (req, res) {
    validateUserForWriteAPI(apps.saveSMSConfiguration, req, res);
});
router.get('/i/apps/getAppAuthState',function(req,res){
    validateUserForWriteAPI(apps.getAppAuthState,req,res);
});
router.get('/i/apps/getKillSwitchState',function(req,res){
    validateUserForDataReadAPI(req,res,apps.getKillSwitchState);
});
router.get('/i/apps/getAppFrequencyCapping',function(req,res){
    validateUserForDataReadAPI(req,res, apps.getAppFrequencyCapping);
});
router.get('/i/apps/getAppDndState',function(req,res){
    validateUserForDataReadAPI(req,res ,apps.getAppDndState);
});
router.get('/i/apps/getChannelAccountData',function(req,res){
    validateUserForDataReadAPI(req, res, apps.getChannelAccountData);
});
router.post('/i/apps/updateFrequencyCapping',csrfProtection ,function(req,res){
    validateUserForWriteAPI(apps.updateFrequencyCapping,req,res);
});
router.post('/i/apps/updateDndValue',csrfProtection,function(req,res){
    validateUserForWriteAPI(apps.updateDndValue,req,res);
});
router.post('/i/apps/updateChannelAccount',csrfProtection,function(req,res){
    validateUserForWriteAPI(apps.updateChannelAccount,req,res);
});
router.get('/o/apps/getFeaturesSettings', function (req, res) {
    validateUserForDataReadAPI(req, res, apps.getFeaturesSettings);
});
router.post('/i/apps/savefeaturesSettings',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.savefeaturesSettings, req, res);
});
router.post('/i/apps/saveallowListSettings',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveallowListSettings, req, res);
});
router.post('/i/apps/saveCampaignSettings',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveCampaignSettings, req, res);
});
router.post('/i/apps/saveAppInboxSettings',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveAppInboxSettings, req, res);
});
router.post('/i/apps/saveEncryptionStatus',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveEncryptionStatus, req, res);
});
router.post('/i/apps/savePushCharLimit',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.savePushCharLimit, req, res);
});
router.get('/o/apps/getPushCharLimit', function (req, res) {
    validateUserForDataReadAPI(req, res, apps.getPushCharLimit);
});
router.get('/o/apps/getPartnerInfo', function (req, res) {
    validateUserForDataReadAPI(req, res, apps.getPartnerInfo);
});
router.post('/i/apps/savePartnerInfo',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.savePartnerInfo, req, res);
});
router.post('/i/apps/saveWebhookThirdPartyApiSettings',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveWebhookThirdPartyApiSettings, req, res);
});
router.post('/i/apps/saveCampConfigurator',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveCampConfigurator, req, res);
});
router.post('/i/apps/removeCampConfigurator',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.removeCampConfigurator, req, res);
});
//campaign Route start 
router.get('/i/templates/createCampaign', function (req, res) {
    validateUserForWriteAPI(template.createCampaign, req, res);
});
router.get('/i/campaigns/update', function (req, res) {
    validateUserForWriteAPI(campaigns.updateCampaign, req, res);
});
router.get('/i/campaigns/delete', function (req, res) {
    validateUserForDataReadAPI(req,res,campaigns.deleteCampaign);
});
router.get('/i/campaigns/run', function (req, res) {
    validateUserForWriteAPI(campaigns.runCampaign, req, res);
});
router.get('/i/campaigns/updateEmailStats', function (req, res) {
    validateUserForWriteAPI(netcoreEmail.updateViewStats, req, res);
});
//validateUserForWriteAPI 
router.get('/o/campaigns/all', function (req, res) {
    validateUserForMgmtReadAPI(req, res, campaigns.getAllCampaigns);
});
router.get('/o/campaigns/transactional', function (req, res) {
    validateUserForMgmtReadAPI(req, res, transaction_camp.sendTransactionalCampaign);
});
router.get('/o/campaigns/getActiveTransactionalCampaigns', function (req, res) {
    validateUserForMgmtReadAPI(req, res, transaction_camp.getActiveCampaigns);
});
router.get('/o/campaigns/getTransactionalCampaignsResponse', function (req, res) {
    validateUserForMgmtReadAPI(req, res, transaction_camp.getTransactionCampaignResponse);
});
router.get('/i/gcm/update', function (req, res) {
    validateUserForWriteAPI(apps.updateGCM, req, res);
});
router.get('/o/appusers/getAppAndUserData', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.getAppAndUserData);
});
 

router.get('/o/users/me', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.getCurrentUser);
});
router.get('/o/users/allUsers', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.getAllUsersNew);
});
router.get('/o/users/updateRole', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.updateRole);
});
router.get('/o/users/resetUserPassword', function (req, res) {
    validateUserForMgmtReadAPI(req, res,users.resetUserPassword);
});
router.get('/o/users/unblockUser', function (req, res) {
    validateUserForMgmtReadAPI(req, res,users.unblockUser);
});
router.get('/o/users/deleteUsersRole', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.deleteUsersRole);
});
router.get('/o/users/deleteUserpermenantly', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.deleteUserpermenantly);
});
router.post('/o/users/addUsersRole',csrfProtection, function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.addUsersRole);
});
router.get('/o/users/validateEmail', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.validateEmail);
});
router.get('/o/users/getAppUsers', function (req, res) {
    validateUserForDataReadAPI(req, res, users.getAppUsers);
});
router.get('/o/users/getAllCompetingAppsUsers', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.getAllCompetingAppsUsers);
});
router.get('/o/users/getUserDetails', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.getUserDetails);
});
router.get('/o/users/getUserRecentActivity', function (req, res) {
    validateUserForMgmtReadAPI(req, res, users.getUserRecentActivity);
});
router.get('/o/apps/getGlobalAppModules', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getGlobalAppModules);
});
router.get('/o/apps/getAppModules', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getAppModules);
});
router.get('/o/apps/getActiveModules', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getActiveModules);
});
router.get('/o/apps/getOtherAppGroups', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getOtherAppGroups);
});
router.get('/o/apps/getChildApps', function (req, res) {
    validateUserForDataReadAPI(req,res, apps.getChildApps);
});
router.get('/o/apps/getAppDetails', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getAppDetails);
});
router.get('/o/apps/getCompetingApps', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getCompetingApps);
});
router.get('/o/apps/getCompetingAppsAppWise', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getCompetingAppsAppWise);
});
router.post('/i/aud/create',csrfProtection ,function (req, res) {
    validateUserForWriteAPI(apps.createAudSegment, req, res);
});
router.post('/i/aud/update', csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.updateAudSegment, req, res);
});

router.get('/i/aud/delete', function (req, res) {
    validateUserForDataReadAPI(req,res,apps.deleteAudSegment);
});
router.get('/o/metrices/getCombinedLogFile', function (req, res) {
    validateUserForMgmtReadAPI(req, res, metrices.getCombinedLogFile);
});
router.get('/o/aud/get_metacustomvariables', function (req, res) {
    validateUserForDataReadAPI(req, res,apps.getMetaCustomVariableFields);
});
router.get('/o/aud/get_metacustomevents', function (req, res) {
    validateUserForDataReadAPI(req, res,apps.getMetaCustomEventFields);
});
router.get('/o/aud/countUserBase', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.countUserBase);
});
router.post('/i/apps/saveSiteSetting',csrfProtection,function (req, res) {
    validateUserForWriteAPI(apps.saveSiteSetting, req, res);
});
router.post('/o/aud/countAudienceReach', function (req, res) {
    validateUserForWriteAPI(apps.countAudienceReach,req, res);
});
router.get('/o/aud/saveGeoFencing', function (req, res) {
    validateUserForMgmtReadAPI(req, res,apps.saveGeoFencing);
});
router.get('/o/aud/getGeoFencing', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getGeoFencing);
});
router.get('/o/aud/delGeoFencing', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.delGeoFencing);
});
router.get('/o/aud/getAudienceSegments', function (req, res) {
    validateUserForDataReadAPI(req, res, apps.getAudienceSegments);
});
router.get('/o/aud/getAudienceSegmentById', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getAudienceSegmentById);
});
router.get('/o/aud/get_metavariables', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.get_metavariables);
});
router.get('/o/aud/getAudienceMatchDids', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getAudienceMatchDids);
});
router.get('/o/aud/validateSegmentName', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.validateSegmentName);
});
router.get('/o/analytics/getAudienceSegments', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getAudienceSegments);
});
router.get('/o/analytics/getAudienceSegmentById', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getAudienceSegmentById);
});
router.get('/o/aud/get_metavariables', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.get_metavariables);
});
router.get('/0/aud/validateSegmentName', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.validateSegmentName);
});

//metrices routes start 
// heatbeat 
router.get('/o/metrices/heartBeat',function(req,res){
    validateUserForHeartBeat(req, res)
})
router.get('/o/metrices/getRawUserData', function (req, res) {
    validateUserForMgmtReadAPI(req, res, metrices.getRawUserData);
});
router.get('/o/apps/getLogs', function (req, res) {
    validateUserForMgmtReadAPI(req, res, apps.getLogs);
});
router.get('/o/metrices/getAllReferals', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getAllReferals);
});
router.get('/o/metrices/getReferalMappings', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getReferalMappings);
});
router.get('/o/metrices/getEventList', (req,res)=>{
    validateUserForDataReadAPI(req,res, devents.getEventList)
})
router.get('/o/metrices/getCSVLogs', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getCSVLogs);
});
router.get('/o/metrices/getReferralCounts', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getReferralCounts);
});

router.get('/o/metrices/getCohortDataForInstalls', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getCohortDataForInstalls);
});
router.get('/o/metrices/getUsersAtRisk', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getUsersAtRisk);
});
router.get('/o/metrices/getEventsStats', function (req, res) {
    validateUserForDataReadAPI(req, res, devents.getEventsStats);
});
router.get('/o/metrices/getEventAttributeStats', function (req, res) {
    validateUserForDataReadAPI(req, res, devents.getEventAttributeStats);
});
router.get('/o/metrices/downloadEventData', function (req, res) {
    validateUserForDataReadAPI(req, res, devents.downloadEventData);
});
router.get('/o/metrices/downloadData', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.downloadData);
});
router.get('/o/metrices/downloadDataCustom', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.downloadDataCustom);
});
// router.get('/o/metrices/getJourneyEventData', djourneys.getjourneyData);
// router.get('/o/metrices/getEventExploreData', devents.getEventExploreData);
// router.get('/o/metrices/getReturningUsersCount', metrices.getReturningUsersCount);
router.get('/o/metrices/downloadEventsStats',function(req,res){
    validateUserForDataReadAPI(req, res, devents.downloadEventsStats);
});
router.get('/o/metrices/downloadEventsAttributeStats',function(req,res){
    validateUserForDataReadAPI(req,res,devents.downloadEventsAttributeStats)
});
// router.get('/o/metrices/downloadJourneyData', metrices.downloadJourneyData);
router.get('/o/metrices/getTotalStats', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getDashboardTotalStats);
});
router.get('/o/metrices/getCampaignStats', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getCampaignStats);
});
router.get('/o/metrices/getInstallUnistallStatsByParam', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getInstallUnistallStatsByParam);
});
router.get('/o/metrices/getInstallUnistallLocation', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getInstallUnistallLocation);
});
router.get('/o/metrices/getActiveUserSessionStats', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserSessionStats);
});
router.get('/o/metrices/getActiveUserSessionStatsDashboard', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserSessionStatsDashboard);
});
router.get('/o/metrices/getDauWauMau', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getDauWauMau);
});
router.get('/o/metrices/getDeviceTotalStats', function(req, res){
    validateUserForDataReadAPI(req, res, metrices.getDeviceTotalStats);
})
router.get('/o/metrices/getActiveUserTimelySessions', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserTimelySessions);
});


router.get('/o/metrices/getDauWauMauWithPlatform', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserDauAndMauWithPlatforms);
});
router.get('/o/metrices/getActiveUserInterests', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserInterests);
});
router.get('/o/metrices/getActiveUserDemographics', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserDemographics);
});
router.get('/o/metrices/getActiveUserCompetingAppStats', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getActiveUserCompetingAppStats);
});



router.get('/o/metrices/getRegainedUsers', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getRegainedUsers);
});

router.get('/o/metrices/getInstallUnistallStatsBySource', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getInstallUnistallStatsBySource);
});

router.get('/o/metrices/getChatBotSession', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getChatBotSession);
});

router.get('/o/metrices/getJourneyList', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getJourneyList);
});
router.get('/o/metrices/getObjectId', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getObjectId);
});
router.get('/o/metrices/deleteJourney', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.deleteJourney);
});
router.get('/o/metrices/getJourney', function (req, res) {
    validateUserForDataReadAPI(req, res, metrices.getJourney);
});
router.get('/o/metrices/getJourneyEventData',function(req,res){
    validateUserForDataReadAPI(req, res, djourneys.getjourneyData)
});
router.post('/o/metrices/updateJourney', csrfProtection, function(req, res){
    validateUserForWriteAPI(metrices.updateJourney,req, res);
})
router.post('/o/metrices/saveJourney',csrfProtection, function (req, res) {
    validateUserForWriteAPI(metrices.saveJourney, req, res);
});
router.post('/o/metrices/savePushToken', function (req, res) {
    validateUserForWriteAPI(metrices.savePushToken, req, res);
});
router.get('/o/metrices/postShortUrl',csrfProtection, function (req, res) {
    validateUserForWriteAPI(metrices.postShortUrl, req, res);
});
router.get('/i/apps/postbaseUrl',function(req,res){
    validateUserForWriteAPI(apps.postbaseUrl,req,res);
});
router.get('/o/metrices/copyJourney', function (req, res) {
    validateUserForWriteAPI(metrices.copyJourney, req, res);
});
router.get('/o/metrices/saveInstallData', function (req, res) {
    validateUserForWriteAPI(metrices.saveInstallData, req, res);
});
router.get('/o/metrices/getInstallData', function (req, res) {
    validateUserForDataReadAPI( req, res,metrices.getInstallData);
});

//funnels
router.get('/o/funnels/getEventFunnels', function(req, res){
    validateUserForDataReadAPI(req, res, funnels.getEventFunnels)
});
router.get('/o/funnels/validateFunnelName', function(req, res){
    validateUserForDataReadAPI(req,res,funnels.validateFunnelName)
});
router.get('/o/funnels/stats', function(req, res){
    validateUserForDataReadAPI( req, res, funnels.getEventFunnelStats);
})
router.get('/o/getFunnel', function(req, res){
    validateUserForDataReadAPI(req, res, devents.getFunnel)
});
router.post('/i/funnels/create',csrfProtection, function(req, res){
    validateUserForDataReadAPI(req, res, funnels.createFunnel)
});
router.get('/i/funnels/delete', function(req, res){
    validateUserForDataReadAPI(req, res, funnels.deleteFunnel )
});
router.get('/i/funnels/getFunnel', function(req, res){
    validateUserForDataReadAPI(req, res, funnels.getFunnelById);
});
router.post('/i/funnels/update',csrfProtection ,function(req, res){
    validateUserForDataReadAPI(req, res, funnels.updateFunnel);
});
router.get('/i/funnels/copy', function(req, res){
    validateUserForWriteAPI(funnels.copyFunnel, req, res) 
});
router.get('/i/startExports',function(req,res){
    validateUserForDataReadAPI(req,res,funnels.startExports)
});
/*get csv list from mongo with status */
router.get('/o/csv/getList', function(req, res){
    validateUserForDataReadAPI(req,res, funnels.getCsvList)
});
/*download Exports csv */
router.get('/o/downloadExportcsv',function(req,res){
    validateUserForDataReadAPI(req, res, funnels.downloadExportcsv);
});
/*delete csv list from mongo */
router.get('/i/csv/delete', function(req, res){
    validateUserForDataReadAPI(req, res, funnels.deleteCsv )
});
router.get('/o/metrices/getAppStats', function (req, res) {
    let urlParts = url.parse(req.url, true);
    let queryString = urlParts.query;
    var params = {
        'qstring':queryString,
        'res':res,
        'req':req,
        'url': urlParts.pathname
    }
    if (params.qstring.args) {
        params.qstring.args = JSON.parse(params.qstring.args);
    }
    validateUserForAppStats(req,res,params, metrices.getAppStats);
});
// Push route start from here 
router.post('/i/push/test', push.test);


module.exports = router;


function validateUserForHeartBeat (req,res){
    let urlParts = url.parse(req.url, true);
    let queryString = urlParts.query;
    var params = {
        'qstring':queryString,
        'res':res,
        'req':req,
        'url': urlParts.pathname
    }
    if (params.qstring.args) {
        params.qstring.args = JSON.parse(params.qstring.args);
    }
    common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
        if (!member || err) {
            common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
            logger.error(`HeartBeat Failing for : ${params.qstring.api_key}`)
            return false;
        }else{
            increaseHeartbeat(member.email)

            function increaseHeartbeat(email) {
            cacheApi.getKey(email,function(err,result){
                if(err || result==null){
                  // When user is not found at Redis Return
                  common.returnMessage(params,401,ErrorMsg.getErrorMessage("UnAuthorizedUser"));
                  logger.error("HeartBeat Failing as User is Unauthorized");
                  return false;
                } else {
                    const sid =  req.cookies.sid;
                    if (result == sid) {
                    // updating the ttl of Key for the next 10 minutes
                    cacheApi.expire(email, tenMinutesInSec);
                    common.returnMessage(params, 200, "User Updated");
                  }else{
                    increaseHeartbeat(email+"_") 
                  }
                }
              });
            }
        }
    }); 
}

function validateUserForAppStats(req,res,params,callback){
    common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
        if (!member || err) {
            common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
            return false;
        }
        else{
            cacheApi.getKey(member.email,function(err,result){
                if(err || result==null){
                        // When user is not found at Redis Return 
                    common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                    return false;                
                }else{
                    // updating the ttl of Key for the next 10 minutes
                    cacheApi.expire(member.email, tenMinutesInSec);   
            params.app_ids=[];
            if(params.qstring.app_id){
                params.app_ids.push(params.qstring.app_id);
                validateUserApiAgentInfo(req,res,callback,params,member.email)
            }
            else{
                if(member.global_admin){
                    common.db.collection('apps').find({"isAppDeleted":{ '$ne': 'true' }}).toArray(function (err, apps) {
                        if(apps){
                            apps.forEach(function(app){
                                params.app_ids.push(app._id);
                            });
                            validateUserApiAgentInfo(req,res,callback,params,member.email)
                        }
                    });
                }
                else{
                    var roles = Object.keys(member.user_role)

                    roles.forEach(function(role) {
                        var roleAppids = member.user_role[role]
                            roleAppids.forEach(function(appid){
                                params.app_ids.push(appid)
                            })
                        })
                    validateUserApiAgentInfo(req,res,callback,params,member.email)
                }
            }
         }
    });            
        }


    });
}

/*middleware function start from here */
function validateUserForSignUp(callback, req, res) {
    let urlParts = url.parse(req.url, true);
    let queryString = urlParts.query;
    var params = {
        'qstring':queryString,
        'res':res,
        'req':req,
        'url': urlParts.pathname
    }
    if (params.qstring.args) {
        params.qstring.args = JSON.parse(params.qstring.args);
    }
    callback(params);
}
function validateUserForWriteAPI(callback, req, res) {
    let urlParts = url.parse(req.url, true);
    let queryString = urlParts.query;
    var params = {
        'qstring':queryString,
        'res':res,
        'req':req,
        'url': urlParts.pathname
    }
    if (params.qstring.args) {
        params.qstring.args = JSON.parse(params.qstring.args);
    }else if(!(Object.keys(req.body).length === 0 && req.body.constructor === Object)){    
            params.qstring = req.body
    }
        //start1 token validation for replay attack
        if(!req.headers.cookie.includes("_csrf")){
            common.returnMessage(params, 401, 'User out of Session');
       }
     const csrf2 = common.getCookieValue(req.headers.cookie, '_csrf');
   
       cacheApi.getKey(csrf2, function(err, responseData) {
           logger.info("redis Get responseData =>",responseData);
           if (err || err != null) {
               common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
           } else {
               if (responseData) {
                   cacheApi.deleteKey(csrf2, function(error, response) {
                       logger.info("error, response  after token validate ", error, "  == ", response);
                   });
                   
                   //start1 end token validation for replay attack
                    //First try to get this user from Cache(Redis), if does not exist then hit mongo. and store back to Cache.
                    cacheApi.getKey(params.qstring.api_key,function(err,result){
                        if(err || result==null){
                            common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
                                if (!member || err) {
                                    common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
                                    return false;
                                }
                                cacheApi.getKey(member.email,function(err,result){
                                    if(err || result==null){
                                            // When user is not found at Redis Return 
                                        common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                                        return false;                
                                    }else{
                                //Write this result back to Redis so that in frequent requests it is served from redis itself.
                                
                                cacheApi.setKey(params.qstring.api_key,JSON.stringify(member));
                                params.member = member;
                                validateUserApiAgentInfo(req,res,callback,params,member.email)
                            }
                        });                            
                            });
                        }
                        else{
                            
                            common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
                                if (!member || err) {
                                    common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
                                    return false;
                                }
                                cacheApi.getKey(member.email,function(err,result){
                                    if(err || result==null){
                                            // When user is not found at Redis Return 
                                        common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                                        return false;                
                                    }else{
                                //Write this result back to Redis so that in frequent requests it is served from redis itself.
                                
                                cacheApi.setKey(params.qstring.api_key,JSON.stringify(member));
                                params.member = member;
                                validateUserApiAgentInfo(req,res,callback,params,member.email)
                            }
                        });  
                            });
                            //callback(params);
                        }
                    });

                    //start2  token validation for replay attack
            } else {
                common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
            }
        }
    })         
      //start2 end token validation for replay attack  
}
function validateUserForDataReadAPI(req, res, callback) {
       
   // if User tries to Pass Url direct from incognito mode return the user
   if(!req.headers.cookie.includes("_csrf")){
    common.returnMessage(params, 401, 'User out of Session');
}
    let urlParts = url.parse(req.url, true);
    let queryString = urlParts.query;
    var params = {
        'qstring':queryString,
        'res':res,
        'req':req,
        'url': urlParts.pathname
    }
    if (params.qstring.args) {
        params.qstring.args = JSON.parse(params.qstring.args);
    }
    common.checkRequestId(params, async function(err, result) {
        if (err) {
            logger.error(`Error while Accessing RequestId  => ${err}`)
            common.returnMessage(params, 401, 'Something went Wrong');
        } else {
            // if Request Id Matches Already within TTL
            if (result) {
                logger.error("Request Id has matched the previous Request")
                common.returnMessage(params, 401, 'Something went Wrong');
                // Process Data As per Business logic
            } else {
                //First try to get this user from Cache(Redis), if does not exist then hit mongo. and store back to Cache.
                cacheApi.getKey(params.qstring.api_key,function(err,result){
                    
                    if(err || result==null){
                        common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
                            if (!member || err) {
                                common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
                                return false;
                            }
                            else{
                                cacheApi.getKey(member.email,function(err,result){
                                    if(err || result==null){
                                        logger.error(`This User is not found at Cache===>Error/Result ${err} ${result}`)
                                            // When user is not found at Redis Return 
                                        common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                                        return false;                
                                    }else{
                                        // updating the ttl of Key for the next 10 minutes
                                        cacheApi.expire(member.email, tenMinutesInSec);   
                                //Write this result back to Redis so that in frequent requests it is served from redis itself.
                                
                                cacheApi.setKey(params.qstring.api_key,JSON.stringify(member));
                                params.member = member;
                                validateApp(req,res,params,callback);
                            }
                        });  
                            }
                        });
                    }
                    else{
                        common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
                            if (!member || err) {
                                common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
                                return false;
                            }
                            else{
                                cacheApi.getKey(member.email,function(err,result){
                                    if(err || result==null){
                                        logger.error(`This User is not found at Cache===>Error/Result ${err} ${result}`)
                                            // When user is not found at Redis Return 
                                        common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                                        return false;                
                                    }else{
                                        // updating the ttl of Key for the next 10 minutes
                                        cacheApi.expire(member.email, tenMinutesInSec);   
                                //Write this result back to Redis so that in frequent requests it is served from redis itself.
                                
                                cacheApi.setKey(params.qstring.api_key,JSON.stringify(member));
                                params.member = member;
                                validateApp(req,res,params,callback);
                                }
                        });                  
                            }
                        });

                    }
                });
            }
        }
    });
}

function validateApp(req,res,params,callback,){
    
    //First try to get this app from Cache(Redis), if does not exist then hit mongo. and store back to Cache.
    cacheApi.getKey(params.qstring.app_id,function(err,result){
        if(err || result==null){
            common.db.collection('apps').findOne({'_id':common.db.ObjectID(params.qstring.app_id + "")}, function (err, app) {
                if (!app) {
                    common.returnMessage(params, 401, 'App does not exist');
                    return false;
                }
                //Write this app back to cache
                cacheApi.setKey(params.qstring.app_id,JSON.stringify(app));
                params.app_id = app['_id'];
                params.appTimezone = app['timezone'];
                params.time = common.initTimeObj(params.appTimezone, params.qstring.uniqueNumber);
                params.defaultuninstallcampaign = app['defaultuninstallcampaign'];
                if(app.createdOn){
                    params.appCreatedOn = app.createdOn;
                }
                validateUserApiAgentInfo(req,res,callback,params,params.member.email)
            });
        }
        else{
            common.db.collection('apps').findOne({'_id':common.db.ObjectID(params.qstring.app_id + "")}, function (err, app) {
                if(!err){
                    var obj = {};
                    obj.key = app.key;
                    obj.name = app.name;
                    if(app.appiceKeys){
                        obj.appiceKeys = app.appiceKeys;
                    }
                    cacheApi.setKey("app_id"+params.qstring.app_id,JSON.stringify(obj));
                }
            })
            var app = JSON.parse(result);
            params.app_id =common.db.ObjectID(app['_id']);
            params.appTimezone = app['timezone'];
            params.time = common.initTimeObj(params.appTimezone, params.qstring.uniqueNumber);
            params.defaultuninstallcampaign = app['defaultuninstallcampaign'];
            if(app.createdOn){
                params.appCreatedOn = app.createdOn;
            }
            validateUserApiAgentInfo(req,res,callback,params,params.member.email)

        }

    });
}

function validateUserForMgmtReadAPI(req, res, callback) {
    let urlParts = url.parse(req.url, true);
    let queryString = urlParts.query;
    var params = {
        'qstring':queryString,
        'res':res,
        'req':req,
        'url': urlParts.pathname
    }
    if (params.qstring.args) {
        params.qstring.args = JSON.parse(params.qstring.args);
    }else if(!(Object.keys(req.body).length === 0 && req.body.constructor === Object)){    
        params.qstring = req.body
    }
    //  Handling undefined : InCase of uniqueNumber is not available from Frontend 
    params.qstring.uniqueNumber = (params.qstring.uniqueNumber) ? params.qstring.uniqueNumber : Date.now()
    common.checkRequestId(params, async function(err, result) {
        if (err) {
            logger.error(`Error while Accessing RequestId  => ${err}`)
            common.returnMessage(params, 401, 'Something went Wrong');
        } else {
            // if Request Id Matches Already within TTL
            if (result) {
                logger.error("Request Id has matched the previous Request")
                common.returnMessage(params, 401, 'Something went Wrong');
                // Process Data As per Business logic
            } else {
                //First try to get this user from Cache(Redis), if does not exist then hit mongo. and store back to Cache.
                cacheApi.getKey(params.qstring.api_key,function(err,result){
                    if(err || result==null){
                        common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
                            if (!member || err) {
                                common.returnMessage(params, 401, ErrorMsg.getErrorMessage('notExist'));
                                return false;
                            }
                            cacheApi.getKey(member.email,function(err,result){
                                if(err || result==null){
                                    logger.error(`This User is not found at Cache===>Error/Result ${err} ${result}`)
                                        // When user is not found at Redis Return 
                                    common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                                    return false;                
                                }else{
                            //Write this result back to Redis so that in frequent requests it is served from redis itself.
                            
                            cacheApi.setKey(params.qstring.api_key,JSON.stringify(member));
                            params.member = member;
                            validateUserApiAgentInfo(req,res,callback,params,member.email)
                        }
                    });     
                        });
                    }
                    else{
                        common.db.collection('members').findOne({'api_key':params.qstring.api_key}, function (err, member) {
                            cacheApi.getKey(member.email,function(err,resultNew){
                                if(err || resultNew==null){
                                    logger.error(`This User is not found at Cache===>Error/resultNew ${err} ${resultNew}`)
                                        // When user is not found at Redis Return 
                                    common.returnMessage(params, 401, ErrorMsg.getErrorMessage('UnAuthorizedUser'));
                                    return false;                
                                }else{
                        
                        params.member = JSON.parse(result);
                        params.member._id = common.db.ObjectID(params.member._id);
                        validateUserApiAgentInfo(req,res,callback,params,member.email)
                    }
                });             
            });
                    }
                });
            }
        }
    });
}

function validateUserApiAgentInfo(req, res, callback, params, email) {
    // remove prefix to make code compatible with IPv6 
  const sid =  req.cookies.sid;

  

    // check requestInfo with the cache details 
    cacheApi.getKey(email, function (err, result) {
        if (err || result == null) {
            // When user is not found at Cache Return
            logger.error(`User not found at cache ==> Failing || Error While Getting user from Redis `)
            logger.error(`Error As in => ${err} and Not found User in redis for Email ${email}`)
        common.returnMessage(params,401,ErrorMsg.getErrorMessage("UnAuthorizedUser"));
        return false;
        } else {
            // Some user found 
            logger.info(`Value Found ${result}`)

            if (result == sid) {
            // updating the ttl of Key for the next 10 minutes
            cacheApi.expire(email, tenMinutesInSec);
            callback(params);
        } else {
            logger.info(`Match Not Found in redis for AgentInfo ${sid}`)
            validateUserApiAgentInfo(req, res, callback, params, email + "_");
        }
        }
    });
        
}

common.checkRequestId = async function(params, callback) {
    if (semusiConfig.hashTupleEnabledTrue) {
        let nonDecodedRequestId;
        nonDecodedRequestId = params.qstring.app_id + params.qstring.api_key + params.qstring.uniqueNumber;
        var requestIdKey = crypto.createHash('sha256').update(nonDecodedRequestId).digest('hex');
        cacheApi.getKey(requestIdKey, function(err, responseData) {
            if (err) {
              
                logger.error("Error while checking the requestID key from cache  =>",err)
                callback(err, true);
            } else {
                if (responseData) {
                   logger.error(`Error :- This RequestId is already Present in Cache ` )
                    logger.info("Redis Response =>",responseData)
                    callback(err, true);
                } else {
                   
                    logger.info(requestIdKey);
                    cacheApi.setKeywithTTL(requestIdKey, true, semusiConfig.ttl);
                    callback(err, false);
                }
            }
        })
    } else {
        callback(null, false);
    }
}