// itemsSlice.ts
import { createSlice } from '@reduxjs/toolkit';
import { deleteListing } from '../api/api'; // Adjust the import as necessary

interface Item {
  id: number;
  // Other item properties
}

interface ItemsState {
  items: Item[];
  loading: boolean;
  error: string | null;
}

const initialState: ItemsState = {
  items: [],
  loading: false,
  error: null,
};

const itemsSlice = createSlice({
  name: 'items',
  initialState,
  reducers: {
    // Add any synchronous reducers here if needed
  },
  extraReducers: (builder) => {
    builder
      .addCase(deleteListing.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(deleteListing.fulfilled, (state, action) => {
        state.loading = false;
        // Remove the item with the ID returned in the action.payload
        state.items = state.items.filter(item => item.id !== action.payload.id);
      })
      .addCase(deleteListing.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || "An error occurred";
      });
  },
});

export default itemsSlice.reducer;
