
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { allAddress, addressUpdate } from '../api/api'; // Update the path as needed

interface AddressState {
  data: any; // Replace `any[]` with the correct type if you know the structure
  loading: boolean;
  error: string | null;
  updateLoading: boolean; // New state for update loading
  updateError: string | null; // New state for update error
  updateSuccess: boolean; // New state for update success
}

const initialState: AddressState = {
  data: [],
  loading: false,
  error: null,
  updateLoading: false,
  updateError: null,
  updateSuccess: false,
};

const addressSlice = createSlice({
  name: 'address',
  initialState,
  reducers: {
    resetUpdateState: (state) => {
      state.updateLoading = false;
      state.updateError = null;
      state.updateSuccess = false;
    }
  },
  extraReducers: (builder) => {
    builder
      // Handling fetching addresses
      .addCase(allAddress.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(allAddress.fulfilled, (state, action: PayloadAction<any[]>) => {
        state.loading = false;
        state.data = action.payload;
      })
      .addCase(allAddress.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch address data';
      })
      
      // Handling address updates
      .addCase(addressUpdate.pending, (state) => {
        state.updateLoading = true;
        state.updateError = null;
        state.updateSuccess = false;
      })
      .addCase(addressUpdate.fulfilled, (state) => {
        state.updateLoading = false;
        state.updateSuccess = true;
      })
      .addCase(addressUpdate.rejected, (state, action) => {
        state.updateLoading = false;
        state.updateError = action.error.message || 'Failed to update address';
      });
  },
});

export const { resetUpdateState } = addressSlice.actions;
export default addressSlice.reducer;

