import { combineReducers } from 'redux';
import { getSuccessActionType } from '../utils';
import { getErrorReducer, getStatusReducer } from './utils/generators';
import { CREATE_STUDENT, FETCH_STUDENT, UPDATE_STUDENT } from '../constants/student';
import { invalidateApiCache } from '../utils/api';
import { FETCH_STUDENT_URL } from '../urls/student';

function data(state = {}, action) {
  switch (action.type) {
    case getSuccessActionType(FETCH_STUDENT):
    case getSuccessActionType(CREATE_STUDENT):
      return Object.fromEntries(Object.entries(action.payload).filter(([key]) => key !== 'user'));
    case getSuccessActionType(UPDATE_STUDENT):
      invalidateApiCache(FETCH_STUDENT_URL);
      return Object.fromEntries(Object.entries(action.payload).filter(([key]) => key !== 'user'));

    default:
      return state;
  }
}

const actionTypes = [FETCH_STUDENT, CREATE_STUDENT];

export default combineReducers({
  status: getStatusReducer(actionTypes),
  error: getErrorReducer(actionTypes),
  data
});
