import { StoreAction } from 'store/utils/actions';
import produce from 'immer';
import { handleRequest, handleResponse } from 'store/utils/reducers';
import auth from 'store/auth';
import actions from './actions';

interface AccountState {
  profile: null | object;
  resource: null | object;
  selectedResource: null | object;
}

const initialState: AccountState = {
  profile: null,
  resource: null,
  selectedResource: null,
};

const treatProfile = (item): Record<string, any> => {
  const newItem = { ...item };

  return newItem;
};

const reducer = (state: AccountState = initialState, action: StoreAction): AccountState =>
  produce(
    state,
    (draft): AccountState => {
      switch (action.type) {
        case actions.profile.request.constant:
          handleRequest(draft, action, 'profile');
          break;
        case actions.profile.result.constant:
          handleResponse(draft, action, 'profile');
          break;
        case actions.updateProfile.result.constant:
          handleResponse(draft, action, 'profile', treatProfile);
          break;
        case actions.loadAccountResource.result.constant: {
          if (!action.status) action.status = 'fulfilled';
          handleResponse(draft, action, 'resource');
          const data = draft.resource.data;
          if (data && data.length && !draft.selectedResource) {
            draft.selectedResource = data[0];
          }
          break;
        }
        case actions.selectAccountResource.constant:
          draft.selectedResource = action.payload;
          break;
        case auth.actions.logout.result.constant:
          draft.profile = null;
          draft.resource = null;
          draft.selectedResource = null;
          break;
        default:
      }
    },
  );

export default reducer;
