import { combineReducers } from 'redux';
import { getSuccessActionType } from '../utils';
import { getErrorReducer, getStatusReducer } from './utils/generators';
import { CHECK_SMS_KEY, CREATE_USER, FETCH_USER, UPDATE_USER_DATA } from '../constants/user';
import { ACCESS_TOKEN_KEY } from '../constants';
import { FETCH_STUDENT } from '../constants/student';
import { invalidateApiCache } from '../utils/api';
import { FETCH_USER_URL } from '../urls/user';

function data(state = {}, action) {
  switch (action.type) {
    case getSuccessActionType(FETCH_USER):
      return action.payload;

    case getSuccessActionType(UPDATE_USER_DATA):
      invalidateApiCache(FETCH_USER_URL);
      return action.payload;

    case getSuccessActionType(FETCH_STUDENT):
      return action.payload.user;

    case getSuccessActionType(CHECK_SMS_KEY):
      return { ...state, mobileVerified: true };

    case getSuccessActionType(CREATE_USER): {
      const { token, ...data } = action.payload;
      localStorage.setItem(ACCESS_TOKEN_KEY, token);
      return data;
    }

    default:
      return state;
  }
}

export default combineReducers({
  status: getStatusReducer([FETCH_USER]),
  error: getErrorReducer([FETCH_USER]),
  data
});
