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 GenericApolloState {
  list: Record<string, any> | null;
}

export const initialState: GenericApolloState = {
  list: {},
};

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

  return newItem;
};

const reducer = (
  state: GenericApolloState = initialState,
  action: StoreAction,
): GenericApolloState =>
  produce(
    state,
    (draft): GenericApolloState => {
      switch (action.type) {
        case actions.list.request.constant:
          handleRequest(draft, action, 'list', true);
          break;
        case actions.list.result.constant:
          handleResponse(draft, action, 'list', treatList);
          break;
        case auth.actions.logout.result.constant:
          draft = initialState;
          break;
        default:
      }
    },
  );

export default reducer;
