package com.kaixed.kchat.repository

import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.UserInfo
import com.kaixed.kchat.data.objectbox.entity.UserInfo_
import com.kaixed.kchat.model.request.UserRequest
import com.kaixed.kchat.model.search.SearchUser
import com.kaixed.kchat.network.RetrofitClient
import com.kaixed.kchat.utils.Constants.MMKV_USER_SESSION
import com.kaixed.kchat.utils.Constants.NICKNAME_KEY
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.tencent.mmkv.MMKV
import okhttp3.MultipartBody

/**
 * @Author: kaixed
 * @Date: 2024/11/23 14:15
 */
class UserProfileRepository {

    private val userApiService = RetrofitClient.userApiService

    // 获取用户信息
    suspend fun getUserInfo(username: String): Result<SearchUser> {
        return try {
            val response = userApiService.getUserInfo(username)
            if (response.isSuccess()) {
                val searchUser = response.getResponseData()
                searchUser?.let {
                    Result.success(searchUser)
                } ?: Result.failure(Exception("用户不存在"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 修改昵称
    suspend fun changeNickname(userRequest: UserRequest): Result<Boolean> {
        return try {
            val response = userApiService.changeNickname(userRequest)
            if (response.isSuccess()) {
                updateNickname(response.getResponseData().toString())
                Result.success(true)
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 上传头像
    suspend fun uploadAvatar(file: MultipartBody.Part, username: String): Result<String> {
        return try {
            val response = userApiService.uploadAvatar(username, file)
            if (response.isSuccess()) {
                val data = response.getResponseData()
                data?.let {
                    updateDb(it)
                    Result.success(it)
                } ?: Result.failure(Exception("请求成功，但返回数据为空"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    private fun updateNickname(newNickname: String) {
        val userInfoBox = get().boxFor(UserInfo::class.java)
        val user = userInfoBox
            .query(UserInfo_.username.equal(getUsername()))
            .build()
            .findFirst()

        MMKV.mmkvWithID(MMKV_USER_SESSION).putString(NICKNAME_KEY, newNickname)

        user?.nickname = newNickname

        if (user != null) {
            userInfoBox.put(user)
        }
    }

    private fun updateDb(url: String) {
        val userInfoBox = get().boxFor(UserInfo::class.java)
        val userInfo =
            userInfoBox.query(UserInfo_.username.equal(getUsername())).build().findFirst()
        if (userInfo != null) {
            userInfo.avatarUrl = url
            userInfoBox.put(userInfo)
        }
    }
}
