//
//  IMUserKit.swift

//
//  Created by Leon on 2025/8/21.
//

import Foundation

class IMUserKit {
    /// 一般在扩展字段里
    var userId: Int?
    var accountId: String?
    var nickname: String?
    var avatar: String?

    var user: V2NIMUser?

    var loadCompleteAction: ((_ user: IMUserKit) -> Void)?

    class func imUserKitWith(accId: String?, completion: ((_ user: IMUserKit?) -> Void)? = nil) -> IMUserKit {
        let kit = IMUserKit()
        // let conversationId = V2NIMConversationIdUtil.p2pConversationId(accountId)
        guard let accountId = accId, accountId.count > 0 else {
            return kit
        }

        // NIMSDK.shared().v2UserService.getUserInfo(accountId, error:)
        NIMSDK.shared().v2UserService.getUserList([accountId]) { user in
            if let searchUser = user.first {
                kit.user = searchUser
                kit.syncDataFrom(nimUser: searchUser)
                completion?(kit)
                kit.loadCompleteAction?(kit)
                
                // dlog("☁️IMUserKit user(V2NIMUser) get:\(user)")
            } else {
                //fatalError("wrong state")
                dlog("☁️IMUserKit ❌user nil")
            }
        } failure: { error in
            dlog("☁️IMUserKit ❌ get user list error:\(error)")
        }

        return kit
    }
    
    class func accountIdWithAIId(aiId:Int) -> String?{
        if aiId <= 0{
            return nil
        }
        if APIConfig.environment == .appStore || APIConfig.environment == .product{
            return "\(aiId)@r"
        }else{
            // Test Envirment
            return "\(aiId)@r@t"
        }
    }

    private func syncDataFrom(nimUser: V2NIMUser?) {
        guard let imUser = nimUser else {
            return
        }

        accountId = imUser.accountId
        nickname = imUser.name
        avatar = imUser.avatar
    }
}
