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

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

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

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

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

export const { setItems } = tokenSlice.actions;

export default tokenSlice.reducer;
