package com.narutohuo.xindazhou.user.datasource.local

import android.content.Context
import android.content.SharedPreferences

/**
 * Token管理器
 * 负责Token的存储、读取和清除
 */
object TokenManager {
    private const val PREFS_NAME = "xdz_auth_prefs"
    private const val KEY_ACCESS_TOKEN = "access_token"
    private const val KEY_REFRESH_TOKEN = "refresh_token"
    private const val KEY_USER_ID = "user_id"
    private const val KEY_SERVER_URL = "server_url"
    private const val KEY_SOCKET_URL = "socket_url"
    
    private var prefs: SharedPreferences? = null
    private var initialized = false
    
    fun init(context: Context) {
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        initialized = true
    }
    
    fun isInitialized(): Boolean = initialized
    
    /**
     * 保存Token
     */
    fun saveToken(accessToken: String, refreshToken: String, userId: Long) {
        prefs?.edit()?.apply {
            putString(KEY_ACCESS_TOKEN, accessToken)
            putString(KEY_REFRESH_TOKEN, refreshToken)
            putLong(KEY_USER_ID, userId)
            apply()
        }
    }
    
    /**
     * 获取Access Token
     */
    fun getAccessToken(): String? {
        return prefs?.getString(KEY_ACCESS_TOKEN, null)
    }
    
    /**
     * 获取Refresh Token
     */
    fun getRefreshToken(): String? {
        return prefs?.getString(KEY_REFRESH_TOKEN, null)
    }
    
    /**
     * 获取用户ID
     */
    fun getUserId(): Long {
        return prefs?.getLong(KEY_USER_ID, 0) ?: 0
    }
    
    /**
     * 判断是否已登录
     */
    fun isLoggedIn(): Boolean {
        return !getAccessToken().isNullOrEmpty()
    }
    
    /**
     * 清除Token（登出）
     */
    fun clearToken() {
        prefs?.edit()?.apply {
            remove(KEY_ACCESS_TOKEN)
            remove(KEY_REFRESH_TOKEN)
            remove(KEY_USER_ID)
            apply()
        }
    }
    
    /**
     * 保存服务器地址
     */
    fun saveServerUrl(url: String) {
        prefs?.edit()?.putString(KEY_SERVER_URL, url)?.apply()
    }
    
    /**
     * 获取服务器地址
     */
    fun getServerUrl(): String? {
        return prefs?.getString(KEY_SERVER_URL, null)
    }
    
    /**
     * 保存Socket地址
     */
    fun saveSocketUrl(url: String) {
        prefs?.edit()?.putString(KEY_SOCKET_URL, url)?.apply()
    }
    
    /**
     * 获取Socket地址
     */
    fun getSocketUrl(): String? {
        return prefs?.getString(KEY_SOCKET_URL, null)
    }
}

