import { URLS } from "../api/apiConfig";
import { TAxios } from "../api/TAxios";
import { SEARCH_DATA_MAX_RESULTS_LIMIT } from "../utils/Config";
import { types } from "./actionTypes";

// Search 통합검색 (IBS) 데이터 조회 IF-LGSP-090
let getSearchKey = null;
export const getSearch =
  (params, startIndex = 1, key) =>
  (dispatch, getState) => {
    const { service, query, domain } = params;
    const maxResults = SEARCH_DATA_MAX_RESULTS_LIMIT;

    let currentKey = key;
    const onSuccess = (response) => {
      console.log("getSearch onSuccess: ", response.data);

      if (startIndex === 1) {
        getSearchKey = new Date();
        currentKey = getSearchKey;

        dispatch({
          type: types.GET_SEARCH,
          payload: response.data,
        });
      } else if (getSearchKey === currentKey) {
        dispatch({
          type: types.GET_SEARCH,
          payload: response.data,
          append: true,
        });
      }

      const stateBeforeLoop = getState();
      const nextStartIndex = response.data.data.result.results.reduce(
        (acc, category) => {
          const { type, total_count } = category;
          const fetchedCount =
            stateBeforeLoop.search.searchDatas[type]?.length ||
            0 + category.docs.length;
          const remainingData = total_count - fetchedCount;

          return remainingData > 0 ? Math.max(acc, fetchedCount + 1) : acc;
        },
        startIndex
      );

      if (nextStartIndex > startIndex) {
        dispatch(getSearch(params, nextStartIndex, currentKey));
      }
    };

    const onFail = (error) => {
      console.error("getSearch onFail: ", error);
    };

    TAxios(
      dispatch,
      getState,
      "post",
      URLS.GET_SEARCH,
      {},
      { service, query, startIndex, maxResults, domain },
      onSuccess,
      onFail
    );
  };

export const resetSearch = (status) => ({
  type: types.RESET_SEARCH,
  payload: status,
});
