package com.bitcointxoko.gudariwallet.service import android.content.Context import timber.log.Timber import com.bitcointxoko.gudariwallet.api.NodeAliasClient as NodeAliasApiClient import com.bitcointxoko.gudariwallet.data.NodeAliasCacheRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow private const val TAG = "NodeAliasService" class NodeAliasService( private val apiClient: NodeAliasApiClient, // ← injected, not duplicated context: Context ) { private val repo = NodeAliasCacheRepository(context) private val _aliases = MutableStateFlow>(emptyMap()) val aliases: StateFlow> = _aliases.asStateFlow() suspend fun warmUp() { _aliases.value = repo.loadAll() } suspend fun resolve(pubkey: String): String? { // 1. Room cache hit repo.get(pubkey)?.let { Timber.d("ALIAS [CACHE HIT ] $pubkey → \"$it\"") return it } // 2. Network via api/NodeAliasService (Retrofit, typed responses) Timber.d("ALIAS [CACHE MISS] $pubkey — fetching from network") val alias = apiClient.resolveAlias(pubkey) ?: run { Timber.w("ALIAS [NOT FOUND ] $pubkey") return null } // 3. Persist to Room repo.put(pubkey, alias) // 4. Publish to StateFlow _aliases.value += (pubkey to alias) Timber.d("ALIAS [FETCHED ] $pubkey → \"$alias\"") return alias } suspend fun clearPersistedCache() { repo.clearAll() _aliases.value = emptyMap() } }