
import { createSlice } from "@reduxjs/toolkit";
import { deleteListing, sellerGetList } from "../api/api";

interface SellerListState {
  sellerListData: { data: any[] }; // ✅ Ensure this matches API response
  loading: boolean;
  error: string | null;
}

const initialState: SellerListState = {
  sellerListData: { data: [] }, // ✅ Match API response format
  loading: false,
  error: null,
};

const sellerListDataSlice = createSlice({
  name: "sellerListData",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      // ✅ Handling DELETE action correctly
      .addCase(deleteListing.pending, (state) => {
        state.loading = true;
      })
      .addCase(deleteListing.fulfilled, (state, action) => {
        state.loading = false;

        if (action.payload?.success) {
          const deletedId = action.meta.arg.id; // ✅ Extract ID from the dispatched action
          state.sellerListData.data = state.sellerListData.data.filter(
            (listing) => listing.id !== deletedId
          );
        } else {
          state.error = "Failed to delete listing"; // Handle API failure
        }
      })
      .addCase(deleteListing.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string || "Delete listing failed";
      })

      // ✅ Handling GET action correctly
      .addCase(sellerGetList.pending, (state) => {
        state.loading = true;
      })
      .addCase(sellerGetList.fulfilled, (state, action) => {
        state.loading = false;
        state.sellerListData = action.payload; // ✅ Update full API response
      })
      .addCase(sellerGetList.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || "Failed to fetch listings";
      });
  },
});

export default sellerListDataSlice.reducer;
