import { types } from "../actions/actionTypes";

const initialState = {
  searchDatas: {},
  totalCount: {},
  searchPerformed: false,
};

export const searchReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_SEARCH: {
      const newResults = action.payload.data.result.results;

      const updatedSearchDatas = action.append ? { ...state.searchDatas } : {};
      newResults.forEach(({ type, docs }) => {
        updatedSearchDatas[type] =
          action.append && updatedSearchDatas[type]
            ? updatedSearchDatas[type].concat(docs)
            : docs;
      });

      const updatedTotalCount = action.append ? { ...state.totalCount } : {};
      newResults.forEach(({ type, total_count }) => {
        updatedTotalCount[type] = total_count;
      });

      return {
        ...state,
        searchDatas: updatedSearchDatas,
        totalCount: updatedTotalCount,
        searchPerformed: true,
      };
    }

    case types.RESET_SEARCH:
      return {
        ...initialState,
      };

    default:
      return state;
  }
};
