import { jwtDecode } from '../utils';

function authReducer (state, { type, token }) {
  if (!state) {
    if (localStorage.authToken) {
      state = {
        type: 'AUTH_LOGIN',
        token: localStorage.authToken
      };
    } return {};
  }
  if (type === 'AUTH_LOGIN') {
    const bigToken = jwtDecode(token);
    if (bigToken) {
      localStorage.setItem('authToken', token);
      return {
        token,
        payload: bigToken
      };
    }
  }
  if (type === 'AUTH_LOGOUT') {
    localStorage.clear();
    return {};
  }
  return state;
}

export default authReducer;
