import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchCategories } from './stock';
import { Categories, CategoriesSliceState, Status } from './types';

const initialState: CategoriesSliceState = {
    categories: [],
    status: Status.LOADING, // loading | success | error
};

const categoriesSlice = createSlice({
  name: 'Categories',
  initialState,
  reducers: {
    setItems(state, action: PayloadAction<Categories[]>) {
      state.categories = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchCategories.pending, (state, action) => {
      state.status = Status.LOADING;
      state.categories = [];
    });

    builder.addCase(fetchCategories.fulfilled, (state, action) => {
      state.categories = action.payload;
      state.status = Status.SUCCESS;
    });

    builder.addCase(fetchCategories.rejected, (state, action) => {
      state.status = Status.ERROR;
      state.categories = [];
    });
  },
});

export const { setItems } = categoriesSlice.actions;

export default categoriesSlice.reducer;
