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

interface FileState {
  list: {} | null;
}

export const initialState: FileState = {
  list: null,
};

export const treatmentIn = values => {
  const output = { ...values };

  return output;
};

const reducer = (state: FileState = initialState, action: StoreAction): FileState => {
  return produce(
    state,
    (draft): FileState => {
      switch (action.type) {
        case actions.list.request.constant:
          handleRequest(draft, action, 'list');
          break;
        case actions.list.result.constant:
          handleResponse(draft, action, 'list');
          break;
        case actions.uploadS3.result.constant:
          // do not add the file to the list if there is a search
          if (draft?.list?.requestData?.search) break;
          handleAddResponse(draft, action, 'list', treatmentIn, true);
          break;
        case actions.filesGetOne.result.constant:
          handleResponse(draft, action, 'detail');
          break;
        case actions.filesGetMine.request.constant:
          handleRequest(draft, action, 'list');
          break;
        case actions.filesGetMine.result.constant:
          handleCountResponse(draft, action, 'list', treatmentIn, 'filesGetMine', 'filesGetMineCount');
          break;
        case auth.actions.logout.result.constant:
          draft.list = null;
          draft.detail = null;
          break;
        default:
      }
    },
  );
};

export default reducer;
