import jwt_decode from "jwt-decode";

const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';

export const actionAuthLogin = (jwt) => {
    return {
        type: LOGIN,
        jwt
    }
}

export const authReducer = (state, action) => {
    console.log('ACTION: ', action)
    if(!state) {
        if(!localStorage.authToken) {
            return {}
        } else {
            // return {
            //     login: jwt_decode(localStorage.authToken).sub.login,
            //     id: jwt_decode(localStorage.authToken).sub.id
            // }
            action.type = LOGIN;
            action.jwt = localStorage.authToken
        }
    }
    
    switch(action.type) {
        case LOGIN: 
            localStorage.authToken = action.jwt;
            return {
                id: jwt_decode(action.jwt).sub.id, 
                login: jwt_decode(action.jwt).sub.login,
                isLogin: true,
                token: action.jwt
            }
        case LOGOUT:
            localStorage.removeItem('authToken');
            return {};
        default:
            return state
    }
}