import { SearchResultsStore } from "searchResults/domain/searchStore";
import * as actionTypes from "./actions/searchActionTypes";
import { AnyAction } from "@reduxjs/toolkit";

type SearchStoreState = Omit<
  SearchResultsStore,
  "search" | "changeSearchRequest"
>;

const ININTIAL_STATE: SearchStoreState = {
  searchRequest: "",
  searchResults: undefined,
  failure: undefined,
  isFailed: false,
  isLoading: false,  
};

const searchResultReducer = (
  state: SearchStoreState = ININTIAL_STATE,
  action: AnyAction
): SearchStoreState => {
  switch (action.type) {
    case actionTypes.CHANGE_SEARCH_REQUEST:
      return {
        ...state,
        searchRequest: action.searchRequest,
      };
    case actionTypes.GET_SEARCH_RESULTS:
      return {
        ...state,
        isLoading: true,
        isFailed: false,
      };
    case actionTypes.GET_SEARCH_RESULTS_SUCCESS:
      return {
        ...state,
        searchResults: action.payload,
        isLoading: false,
        isFailed: false,
      };
      case actionTypes.GET_SEARCH_RESULTS_FAILURE:
      return {
        ...state,
        isFailed: true,
        failure: action.payload,
        isLoading: false,
      };
    default:
      return state;
  }
};

export { searchResultReducer };
export type { SearchStoreState };
