import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import type {MenuResponse} from '@/pages/System/Menu/types';

interface UserInfo {
    id: number;
    username: string;
    nickname?: string;
    email?: string;
    phone?: string;
}

interface UserState {
    token: string | null;
    userInfo: UserInfo | null;
    menus: MenuResponse[];
}

const initialState: UserState = {
    token: localStorage.getItem('token'),
    userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')!) : null,
    menus: localStorage.getItem('menus') ? JSON.parse(localStorage.getItem('menus')!) : []
};

const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        setToken: (state, action: PayloadAction<string>) => {
            state.token = action.payload;
            localStorage.setItem('token', action.payload);
        },
        setUserInfo: (state, action: PayloadAction<UserInfo>) => {
            state.userInfo = action.payload;
            localStorage.setItem('userInfo', JSON.stringify(action.payload));
        },
        setMenus: (state, action: PayloadAction<MenuResponse[]>) => {
            state.menus = action.payload;
            localStorage.setItem('menus', JSON.stringify(action.payload));
        },
        logout: (state) => {
            state.token = null;
            state.userInfo = null;
            state.menus = [];
            localStorage.removeItem('token');
            localStorage.removeItem('tenantId');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('menus');
        }
    }
});

export const {setToken, setUserInfo, setMenus, logout} = userSlice.actions;
export default userSlice.reducer; 