



import { createSlice } from '@reduxjs/toolkit';
import { categoryApiCall } from '../api/api'; 

interface categoryState {
  categories: any;
  selectedCategory: { id: number | null; name: string | null };
  loading: boolean;
  error: string | null;
}

const initialState: categoryState = {
  categories: [],
  selectedCategory: { id: null, name: null },
  loading: false,
  error: null,
};

const categorySlice = createSlice({
  name: 'categories',
  initialState,
  reducers: {
    // Action to set the selected category
    setSelectedCategory(state, action) {
      state.selectedCategory = action.payload;
    },
    clearSelectedCategory(state) {
      state.selectedCategory = { id: null, name: null };
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(categoryApiCall.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(categoryApiCall.fulfilled, (state, action) => {
        state.loading = false;
        state.categories = action.payload;
      })
      .addCase(categoryApiCall.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch categories';
      });
  },
});

export const { setSelectedCategory, clearSelectedCategory } = categorySlice.actions;

export default categorySlice.reducer;

