package com.rosetta.messenger.network.connection

import com.rosetta.messenger.network.PacketSearch
import com.rosetta.messenger.network.SearchUser
import com.rosetta.messenger.session.IdentityStore
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class OwnProfileSyncService(
    private val isPlaceholderAccountName: (String?) -> Boolean,
    private val updateAccountName: suspend (publicKey: String, name: String) -> Unit,
    private val updateAccountUsername: suspend (publicKey: String, username: String) -> Unit
) {
    private val _ownProfileUpdated = MutableStateFlow(0L)
    val ownProfileUpdated: StateFlow<Long> = _ownProfileUpdated.asStateFlow()

    fun notifyOwnProfileUpdated() {
        _ownProfileUpdated.value = System.currentTimeMillis()
    }

    suspend fun applyOwnProfileFromSearch(
        ownPublicKey: String,
        user: SearchUser
    ): Boolean {
        if (ownPublicKey.isBlank()) return false
        if (!user.publicKey.equals(ownPublicKey, ignoreCase = true)) return false

        if (user.title.isNotBlank() && !isPlaceholderAccountName(user.title)) {
            updateAccountName(ownPublicKey, user.title)
        }
        if (user.username.isNotBlank()) {
            updateAccountUsername(ownPublicKey, user.username)
        }
        IdentityStore.updateOwnProfile(user, reason = "protocol_search_own_profile")
        _ownProfileUpdated.value = System.currentTimeMillis()
        return true
    }

    fun buildOwnProfilePacket(publicKey: String?, privateHash: String?): PacketSearch? {
        val normalizedPublicKey = publicKey?.trim().orEmpty()
        val normalizedPrivateHash = privateHash?.trim().orEmpty()
        if (normalizedPublicKey.isEmpty() || normalizedPrivateHash.isEmpty()) return null

        return PacketSearch().apply {
            this.privateKey = normalizedPrivateHash
            this.search = normalizedPublicKey
        }
    }
}
