import SwiftUI
import Combine

/// 管理用户认证状态的类
public class AuthState: ObservableObject {
    @Published public var isAuthenticated: Bool = false {
        didSet {
            print("🔔 认证状态变更: \(isAuthenticated ? "已登录" : "已登出")")
        }
    }
    @Published public var isLoading = false
    @Published public var errorMessage: String?
    @Published public var user: User?
    
    // 单例模式
    public static let shared = AuthState()
    
    private init() {}
    
    /// 登录成功时调用
    public func login(user: User? = nil) {
        if let user = user {
            self.user = user
        }
        isAuthenticated = true
        errorMessage = nil
    }
    
    /// 登出时调用
    public func logout() {
        print("👋 用户登出")
        user = nil
        isAuthenticated = false
        
        // 清除用户数据
        TokenManager.shared.clearTokens()
        UserDefaults.standard.removeObject(forKey: "lastLoginUser")
    }
    
    /// 更新加载状态
    public func setLoading(_ loading: Bool) {
        isLoading = loading
    }
    
    /// 设置错误信息
    public func setError(_ message: String) {
        errorMessage = message
    }
}
