// promiseReducer
import { combineReducers } from "redux"

export function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
    if (type === 'PROMISE') {
        return {
            ...state,
            [nameOfPromise]: { status, payload, error }
        }
    }
    return state
}

// localStoredReducer
export function localStoredReducer(originalReducer, localStorageKey) {
    function wrapper(state, action) {
        if (!state) {
            try {
                return JSON.parse(localStorage[localStorageKey])
            }
            catch (error) {

            }
        }
        const newState = originalReducer(state, action)
        localStorage[localStorageKey] = JSON.stringify(newState)

        return newState
    }

    return wrapper
}

// authReducer
// раскодируем JWT-токен
const jwtDecode = function (token) {
    try {
        let parseData = token.split('.')[1]
        return JSON.parse(atob(parseData))
    }
    catch (e) {
        return undefined
    }
}

export function authReducer(state = {}, { type, token }) {
    if (type === 'AUTH_LOGIN') {

        let payload = jwtDecode(token)

        return state = {
            token,
            payload
        }
    }

    if (type === 'AUTH_LOGOUT') {
        localStorage.removeItem('authToken')
        return {}
    }

    return state
}


// 1 изменение 
export const reducers = {
    promise: localStoredReducer(promiseReducer, 'promise'),
    auth: localStoredReducer(authReducer, 'auth'),
    // cart: localStoredReducer(cartReducer, 'cart'),
}

export const totalReducer = combineReducers(reducers)

