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

const initialState: LoginSliceState = {
  token: [],
  status_token: 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(fetchToken.pending, (state, action) => {
      state.token = [];
      state.status_token = Status.LOADING;
      console.log(state.token);
    });

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

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

export const { setItems } = tokenSlice.actions;

export default tokenSlice.reducer;
