import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {jwtDecode, JwtPayload} from "jwt-decode";

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

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

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        login: (state, action: PayloadAction<{ accessToken: string }>) => {
            try {
                const {sub} = jwtDecode<JwtPayload>(action.payload.accessToken);
                state.accessToken = action.payload.accessToken;
                state.isAuthorized = true;
                if (sub === "guest")
                    state.isGuest = true;
            } catch (_) {
                const url = window.location.href;
                const urlObj = new URL(url);
                urlObj.search = '';
                history.replaceState(null, '', urlObj);
                window.location.reload();
            }
        },
        logout: (state) => {
            state.isAuthorized = false;
            state.accessToken = '';
        }
    }
})
export const {login, logout} = authSlice.actions;
export default authSlice.reducer;