import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchUser } from './asyncActions';
import { User, Status, UserSliceState } from './types';

const initialState: UserSliceState = {
    user_items: [],
    user_status: Status.LOADING, // loading | success | error
};

const userSlice = createSlice({
  name: 'categories',
  initialState,
  reducers: {
    setUser(user_status, action: PayloadAction<User[]>) {
        user_status.user_items = action.payload;
    },
  },

  extraReducers: (builder) => {
    builder.addCase(fetchUser.pending, (user_status) => {
        user_status.user_status = Status.LOADING;
        user_status.user_items = [];
    });

    builder.addCase(fetchUser.fulfilled, (user_status, action) => {
        user_status.user_status = Status.SUCCESS;
        user_status.user_items = action.payload;
    });

    builder.addCase(fetchUser.rejected, (user_status) => {
        user_status.user_status = Status.ERROR;
        user_status.user_items = [];
    });
  },
});

export const { setUser } = userSlice.actions;

export default userSlice.reducer;