package com.example.ops_android.data.cache

import com.example.ops_android.data.model.UserDetail
import com.example.ops_android.data.remote.api.UsersApi
import kotlinx.coroutines.CompletableDeferred
import java.util.concurrent.ConcurrentHashMap

class UserCache(
    private val usersApi: UsersApi
) {
    private val cache = ConcurrentHashMap<Int, UserDetail>()
    private val inflightRequests = ConcurrentHashMap<Int, CompletableDeferred<UserDetail?>>()

    suspend fun fetchUserInfo(userID: Int): UserDetail? {
        if (userID == 0) return null

        cache[userID]?.let { return it }

        inflightRequests[userID]?.let { return it.await() }

        val deferred = CompletableDeferred<UserDetail?>()
        inflightRequests[userID] = deferred

        try {
            val response = usersApi.getUserInfoFromUserID(userID)
            val info = if (response.errCode == 0 && response.data?.userinfo != null) {
                response.data.userinfo.also { cache[userID] = it }
            } else {
                null
            }
            deferred.complete(info)
            return info
        } catch (e: Exception) {
            deferred.complete(null)
            return null
        } finally {
            inflightRequests.remove(userID)
        }
    }

    fun getUsername(userID: Int): String {
        if (userID == 0) return ""
        val user = cache[userID]
        return user?.Username ?: "用户$userID"
    }

    fun getCachedUser(userID: Int): UserDetail? = cache[userID]

    fun clear() {
        cache.clear()
    }
}
