import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { storeListing, updateSellerListing } from '../api/api'; // Import the async thunks

interface StoreState {
  storeData: any;
  update: any;
  loading: boolean;
  error: string | null;
}

const initialState: StoreState = {
  storeData: null,
  update:null,
  loading: false,
  error: null,
};

const StoreListingState = createSlice({
  name: 'store',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    // Handling storeListing API
    builder
      .addCase(storeListing.pending, (state) => {
        state.loading = true;
      })
      .addCase(storeListing.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;
        state.storeData = action.payload;
      })
      .addCase(storeListing.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch store listing';
      });

    // Handling updateSellerListing API
    builder
      .addCase(updateSellerListing.pending, (state) => {
        state.loading = true;
      })
      .addCase(updateSellerListing.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;
        // Update the storeData with the updated listing data
        state.update = state.update?.map((item: any) => 
          item.id === action.payload.id ? action.payload : item
        );
      })
      .addCase(updateSellerListing.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to update seller listing';
      });
  },
});

export default StoreListingState.reducer;
