const jwtDecode = token => {
    try {
        let arrToken = token.split('.')
        let base64Token = atob(arrToken[1])
        return JSON.parse(base64Token)
    }catch (e) {
        console.log('Лажа, Бро ' + e);
    }
}

function authReducer(state, { type, token }) {
    if (!state) {
        if (localStorage.authToken) {
            type = 'LOGIN'
            token = localStorage.authToken
        } else state = {}
    }
    if (type === 'LOGIN') {
        localStorage.setItem('authToken', token)
        let payload = jwtDecode(token)
        if (typeof payload === 'object') {
            return {
                ...state,
                token,
                payload
            }
        } else return state
    }
    if (type === 'LOGOUT') {
        localStorage.removeItem('authToken')
        return {}
    }
    return state
}

export default authReducer;
