
import { createSlice } from '@reduxjs/toolkit';
import { viewListing, createBid } from '../api/api';

interface ViewListingState {
    data: any; 
    loading: boolean;
    error: string | null;
}

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

const listingsSlice = createSlice({
    name: 'listings',
    initialState,
    reducers: {
        // Reducer to handle adding a bid manually
        addBid(state, action) {
            if (state.data && state.data.listing && state.data.listing.bids) {
                state.data.listing.bids.push(action.payload);
            }
        },
        reset() {
            return initialState;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(viewListing.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            .addCase(viewListing.fulfilled, (state, action) => {
                state.loading = false;
                state.data = action.payload;
            })
            .addCase(viewListing.rejected, (state, action) => {
                state.loading = false;
                state.error = action.payload as string;
            })
            .addCase(createBid.fulfilled, (state, action) => {
                // Update listing with the new bid when createBid is successful
                if (state.data && state.data.listing && state.data.listing.bids) {
                    state.data.listing.bids.push(action.payload);
                }
            });
    },
});

export const { addBid, reset } = listingsSlice.actions;
export default listingsSlice.reducer;