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

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

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

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

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

export const { setCategories } = categoriesSlice.actions;

export default categoriesSlice.reducer;
