/**
 * 认证相关组合式函数
 */
import { 
    saveAccessToken, 
    getAccessToken, 
    clearAccessToken,
    saveUserInfo,
    getUserInfo,
    clearUserInfo,
    clearAll
} from '../utils/storage'
import type { UserInfo } from '../types/user'

// 定义返回类型
type AuthComposable = {
    saveLoginInfo: (accessToken: string, userInfo: UTSJSONObject) => void
    getCurrentUserInfo: () => UTSJSONObject | null
    getCurrentAccessToken: () => string | null
    isLoggedIn: () => boolean
    logout: () => void
}

/**
 * 认证管理
 */
export const useAuth = (): AuthComposable => {
    /**
     * 保存登录信息
     */
    const saveLoginInfo = (accessToken: string, userInfo: UTSJSONObject): void => {
        saveAccessToken(accessToken)
        saveUserInfo(userInfo)
    }

    /**
     * 获取当前用户信息
     */
    const getCurrentUserInfo = (): UTSJSONObject | null => {
        return getUserInfo()
    }

    /**
     * 获取当前 AccessToken
     */
    const getCurrentAccessToken = (): string | null => {
        return getAccessToken()
    }

    /**
     * 检查是否已登录
     */
    const isLoggedIn = (): boolean => {
        const token = getAccessToken()
        return token != null && token.length > 0
    }

    /**
     * 退出登录
     */
    const logout = (): void => {
        clearAll()
        // 设置退出标志，防止自动登录
        uni.setStorageSync('isLogout', true)
        // 触发登录状态变化事件
        uni.$emit('onAuthStateChange', { isLoggedIn: false })
        // 跳转登录页
        uni.reLaunch({
            url: '/pages/login/index'
        })
    }

    return {
        saveLoginInfo,
        getCurrentUserInfo,
        getCurrentAccessToken,
        isLoggedIn,
        logout
    }
}

