import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchLogin } from './stock';
import { Token, LoginSliceState, Status } from './types';

const initialState: LoginSliceState = {
  items: Token.token,
  status: Status.LOADING, // loading | success | error
};

const loginSlice = createSlice({
  name: 'login',
  initialState,
  reducers: {
    setItems(state, action: PayloadAction<Token[]>) {
      state.items = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchLogin.pending, (state, action) => {
      state.status = Status.LOADING;
      state.items = [];
    });

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

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

export const { setItems } = loginSlice.actions;

export default loginSlice.reducer;
