import {createSlice, PayloadAction} from "@reduxjs/toolkit";

interface AuthState {
    isAuthorized: boolean;
    accessToken: string;
}

const initialState = (): AuthState => {
    const localStorageState = localStorage.getItem("authState");
    if (localStorageState !== null) {
        return JSON.parse(localStorageState);
    }
    return {
        accessToken: "",
        isAuthorized: false
    }
}

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        login: (state, action: PayloadAction<{ accessToken: string }>) => {
            state.accessToken = action.payload.accessToken;
            state.isAuthorized = true;
        },
        logout: (state) => {
            state.isAuthorized = false;
            state.accessToken = '';
        }
    }
})
export const {login, logout} = authSlice.actions;
export default authSlice.reducer;