import { types } from "../actions/actionTypes";
import { GET_MY_INFO_ORDER_SEARCH_LIMIT } from "../utils/Config";

const initialState = {
  orderDetailData: {},
  orderInfoData: {},
  cancelOrderInfoData: {},
  orderShippingData: {},
  orderSearchParams: {
    mbrNo: null,
    srchMonth: null,
    cancelOrderYn: null,
    limitNum: GET_MY_INFO_ORDER_SEARCH_LIMIT,
  },
};

export const orderReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_MY_INFO_ORDER_DETAIL_SEARCH:
      return {
        ...state,
        orderDetailData: action.payload,
      };

    case types.GET_MY_INFO_ORDER_SEARCH: {
      const newResults = action.payload.orderInfo || [];
      const orderInfoCount = action.payload.orderInfoCount;
      const { cancelOrderYn } =
        action.orderSearchParams || state.orderSearchParams;

      if (cancelOrderYn === "Y") {
        if (action.append) {
          const existingData = state.cancelOrderInfoData.orderInfo || [];
          const combinedData = [...existingData, ...newResults];

          return {
            ...state,
            cancelOrderInfoData: {
              ...state.cancelOrderInfoData,
              orderInfo: combinedData,
              orderInfoCount,
            },
          };
        } else {
          return {
            ...state,
            cancelOrderInfoData: {
              ...action.payload,
            },
            orderSearchParams: action.orderSearchParams,
          };
        }
      } else {
        if (action.append) {
          const existingData = state.orderInfoData.orderInfo || [];
          const combinedData = [...existingData, ...newResults];

          return {
            ...state,
            orderInfoData: {
              ...state.orderInfoData,
              orderInfo: combinedData,
              orderInfoCount,
            },
          };
        } else {
          return {
            ...state,
            orderInfoData: {
              ...action.payload,
            },
            orderSearchParams: action.orderSearchParams,
          };
        }
      }
    }

    case types.CLEAR_MY_INFO_ORDER_SEARCH: {
      return {
        ...state,
        orderInfoData: {},
        cancelOrderInfoData: {},
      };
    }

    case types.GET_MY_INFO_ORDER_SEARCH_CANCEL:
      return {
        ...state,
        orderCancelData: action.payload,
      };

    case types.GET_MY_INFO_ORDER_SHIPPING_SEARCH:
      return {
        ...state,
        orderShippingData: action.payload,
      };

    default:
      return state;
  }
};
