import { types } from '../actions/actionTypes'; /** * Cart Reducer 초기 상태 */ const initialState = { // 장바구니 조회 데이터 getMyinfoCartSearch: { cartList: [], totalCount: 0, }, selectCart : { cartList: [], checkedItems: [], // ✅ 체크된 상품 정보 저장 totalCount: 0, }, // 추가/수정/삭제 결과 lastAction: null, error: null, }; /** * Cart Reducer * 장바구니 관련 상태를 관리합니다. */ export const cartReducer = (state = initialState, action) => { switch (action.type) { // 장바구니 조회 - API에서 가져온 전체 목록 case types.GET_MY_INFO_CART_SEARCH: return { ...state, getMyinfoCartSearch: action.payload || { cartList: [], totalCount: 0, }, error: null, }; // 장바구니에 상품 추가 case types.INSERT_MY_INFO_CART: return { ...state, selectCart: { ...state.selectCart, cartList: [...state.selectCart.cartList, action.payload], totalCount: (state.getMyinfoCartSearch.totalCount || 0) + 1, }, }; //체크박스 토글시 상품 처리 case types.TOGGLE_CHECK_CART: { const checkedItem = action.payload.item; const isChecked = action.payload.isChecked; let updatedCheckedList = state.selectCart?.checkedItems || []; if (isChecked) { const itemExists = updatedCheckedList.some( item => item.prodSno === checkedItem.prodSno ); if (!itemExists) { updatedCheckedList = [...updatedCheckedList, checkedItem]; } } else { updatedCheckedList = updatedCheckedList.filter( item => item.prodSno !== checkedItem.prodSno ); } return { ...state, selectCart: { ...state.selectCart, checkedItems: updatedCheckedList, totalCount: updatedCheckedList.length, }, }; } // 장바구니에서 상품 삭제 case types.DELETE_MY_INFO_CART: return { ...state, getMyinfoCartSearch: { ...state.getMyinfoCartSearch, cartList: (state.getMyinfoCartSearch.cartList || []).filter( item => item.prodSno !== action.payload.prodSno ), totalCount: Math.max(0, (state.getMyinfoCartSearch.totalCount || 0) - 1), }, }; case types.UPDATE_MY_INFO_CART: return { ...state, getMyinfoCartSearch: { ...state.getMyinfoCartSearch, cartList: (state.getMyinfoCartSearch.cartList || []).map(item => item.prodSno === action.payload.prodSno ? { ...item, ...action.payload } : item ), }, }; // 장바구니에 상품 추가 (addToCart - 로컬 상태용) case types.ADD_TO_CART: return { ...state, lastAction: { type: "add", data: action.payload, timestamp: Date.now(), }, error: null, }; // 장바구니에서 상품 제거 (removeFromCart) case types.REMOVE_FROM_CART: return { ...state, lastAction: { type: "remove", data: action.payload, timestamp: Date.now(), }, error: null, }; // 장바구니 상품 수량 업데이트 (updateCartItem) case types.UPDATE_CART_ITEM: return { ...state, lastAction: { type: "updateQty", data: action.payload, timestamp: Date.now(), }, error: null, }; // 장바구니 전체 비우기 (clearCart - 로컬 상태 전용) case types.CLEAR_CART: return { ...state, getMyinfoCartSearch: { cartList: [], totalCount: 0, }, lastAction: { type: "clear", timestamp: Date.now(), }, error: null, }; default: return state; } };