package com.rosetta.messenger.network.connection

import com.rosetta.messenger.network.Protocol
import com.rosetta.messenger.network.ProtocolState
import kotlinx.coroutines.flow.StateFlow

class ProtocolInstanceManager(
    private val serverAddress: String,
    private val addLog: (String) -> Unit,
    private val isNetworkAvailable: () -> Boolean,
    private val onNetworkUnavailable: () -> Unit
) {
    @Volatile private var protocol: Protocol? = null
    private val protocolInstanceLock = Any()

    fun getOrCreateProtocol(): Protocol {
        protocol?.let { return it }

        synchronized(protocolInstanceLock) {
            protocol?.let { return it }

            val created =
                Protocol(
                    serverAddress = serverAddress,
                    logger = { msg -> addLog(msg) },
                    isNetworkAvailable = isNetworkAvailable,
                    onNetworkUnavailable = onNetworkUnavailable
                )
            protocol = created
            addLog("🧩 Protocol singleton created: id=${System.identityHashCode(created)}")
            return created
        }
    }

    val state: StateFlow<ProtocolState>
        get() = getOrCreateProtocol().state

    val lastError: StateFlow<String?>
        get() = getOrCreateProtocol().lastError

    fun disconnect(clearCredentials: Boolean) {
        protocol?.disconnect()
        if (clearCredentials) {
            protocol?.clearCredentials()
        }
    }

    fun destroy() {
        synchronized(protocolInstanceLock) {
            protocol?.destroy()
            protocol = null
        }
    }

    fun isAuthenticated(): Boolean = protocol?.isAuthenticated() ?: false

    fun isConnected(): Boolean = protocol?.isConnected() ?: false
}
