import axios from 'axios'
import {UserActionTypes} from '../redux/user/action.types'

const withStore = (token, dispatch) => {


    const _axiosApiInstance = axios.create()

    // Request interceptor for API calls
    _axiosApiInstance.interceptors.request.use(
        config => {

        config.headers = { 
            'Authorization': `Basic ${token}` 
        }
        return config;
        },
        error => {
        Promise.reject(error)
    })

    // Response interceptor for API calls
    _axiosApiInstance.interceptors.response.use((response) => {
        
        //if refresh token is present        
        const refresh_token = response.headers["crt"]
        if(!!refresh_token && !!dispatch){            
            console.log('the response ', refresh_token)
            dispatch({
                type: UserActionTypes.UPDATE_ACCESS_TOKEN,
                payload: refresh_token
            })
        }
        return response
    }, (exception) => {
        /*
        const originalRequest = error.config;
        if (error.response.status === 403 && !originalRequest._retry) {
        originalRequest._retry = true;
        const access_token = await refreshAccessToken();            
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
        return axiosApiInstance(originalRequest);
        }
        */
        if(exception.response.status === 401){
            const title =  `${exception.response.data}: ${exception.message}. Please Re-Login`
            const updatedException = { ...exception }
            updatedException.response.data = {title }
            return Promise.reject(updatedException)
            }
        else{
            return Promise.reject(exception)
        }
    })

    return {
        getService: _axiosApiInstance
    }
}

const handleAuthenticationFailed = (exception, dispatch, cb) => {
    exception.response.status === 401 ?
            dispatch(cb( `${exception.response.data}: ${exception.message}. Please Re-Login`)):
            dispatch(cb( exception.response.data.title))
}

export { withStore, axios, handleAuthenticationFailed }