import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Wishlist, DeleteWishlist,  } from '../api/api'; // Import all thunks

interface WishlistState {
  data: any; // Ensure data is always an array
  loading: boolean;
  error: string | null;
}

const initialState: WishlistState = {
  data: [],
  loading: false,
  error: null,
};

const wishlistSlice = createSlice({
  name: 'wishlist',
  initialState,
  reducers: {
    // Define any additional reducers here if needed
  },
  extraReducers: (builder) => {
    builder
      // Handling adding items to wishlist
      .addCase(Wishlist.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(Wishlist.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;
        if (Array.isArray(state.data)) {  
          state.data.push(action.payload); // Add the new wishlist item to the array
        }
      })
  
      .addCase(Wishlist.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to add item to wishlist';
      })

      // Handling deleting items from wishlist
      .addCase(DeleteWishlist.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(DeleteWishlist.fulfilled, (state, action: PayloadAction<{ id: string }>) => {
        state.loading = false;
        if (Array.isArray(state.data)) {
          state.data = state.data.filter((item: any) => item.id !== action.payload.id);
        }
      })
      .addCase(DeleteWishlist.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to delete item from wishlist';
      });
  },
});

export default wishlistSlice.reducer;
