import type { AnyAction } from "redux";
import { UserStore } from "../domain/userStore";
import * as actionTypes from "./userActionTypes";

type UserStoreState = Omit<UserStore, "loadUser" | "setUser" | "toggleUserTwoFactor" | "updateUser">;

const INITIAL_STATE: UserStoreState = {
  user: undefined,
  isLoading: false,
  isUpdating: false
};

const userReducer = (state: UserStoreState = INITIAL_STATE, action: AnyAction): UserStoreState => {
  switch (action.type) {
    case actionTypes.SET_USER:
      return { ...state, user: action.user };
    case actionTypes.GET_USER:
      return { ...state, isLoading: true };
    case actionTypes.GET_USER_SUCCESS:
      return { ...state, isLoading: false, user: action.user };
    case actionTypes.UPDATE_USER:
      return { ...state, isUpdating: true };
    case actionTypes.UPDATE_USER_SUCCESS:
      return { ...state, isUpdating: false };
    case actionTypes.TOGGLE_TWO_FACTOR:
      return { ...state, user: {...action.user, twoFactorEnabled: !action.user.twoFactorEnabled} };
    default:
      return state;
  }
};

export { userReducer };
export type { UserStoreState };