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.RegisterRequest
import com.kaixed.kchat.model.response.register.Register
import com.kaixed.kchat.network.RetrofitClient
import com.kaixed.kchat.utils.Constants.MMKV_USER_SESSION
import com.tencent.mmkv.MMKV
import io.objectbox.Box

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

    private val userApiService = RetrofitClient.userApiService

    private val userInfoBox: Box<UserInfo> by lazy { get().boxFor(UserInfo::class.java) }

    private val mmkv by lazy { MMKV.mmkvWithID(MMKV_USER_SESSION) }

    // 用户注册
    suspend fun register(registerRequest: RegisterRequest): Result<Register> {
        return try {
            val response = userApiService.register(registerRequest)
            if (response.isSuccess()) {
                val register = response.getResponseData()
                register?.let {
                    val userInfo = UserInfo(
                        username = register.username,
                        nickname = register.nickname,
                        avatarUrl = "",
                        signature = "",
                        telephone = registerRequest.telephone
                    )
                    userInfoBox.put(userInfo)

                    Result.success(register)
                } ?: Result.failure(Exception("注册成功，但未返回用户数据"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 登录方法
    suspend fun loginByUsername(username: String, password: String): Result<UserInfo> {
        return try {
            val response = userApiService.loginByUsername(username, password)
            if (response.isSuccess()) {
                val userInfo = response.getResponseData()
                if (userInfo != null) {
                    updateDb(userInfo)
                    Result.success(userInfo)
                } else {
                    Result.failure(Exception("登录成功，但未返回用户数据"))
                }
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    private fun updateDb(userInfo: UserInfo) {
        mmkv.apply {
            encode("username", userInfo.username)
            encode("nickname", userInfo.nickname)
            encode("avatarUrl", userInfo.avatarUrl)
        }
        MMKV.defaultMMKV().encode("userLoginStatus", true)
        val user = userInfoBox
            .query(UserInfo_.username.equal(userInfo.username))
            .build()
            .findFirst()
        if (user == null) {
            userInfoBox.put(userInfo)
        }
    }

    suspend fun loginByTelephone(telephone: String, password: String): Result<UserInfo> {
        return try {
            val response = userApiService.loginByTelephone(telephone, password)
            if (response.isSuccess()) {
                val userInfo = response.getResponseData()
                userInfo?.let {
                    updateDb(userInfo)
                    Result.success(userInfo)
                } ?: Result.failure(Exception("登录成功，但未返回用户数据"))
            } else {
                Result.failure(Exception(response.getResponseMsg()))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
