package com.rosetta.messenger.ui.auth

import com.rosetta.messenger.network.ProtocolManager
import com.rosetta.messenger.network.ProtocolState
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull

internal fun startAuthHandshakeFast(publicKey: String, privateKeyHash: String) {
    // Desktop parity: start connection+handshake immediately, without artificial waits.
    ProtocolManager.connect()
    ProtocolManager.authenticate(publicKey, privateKeyHash)
    ProtocolManager.reconnectNowIfNeeded("auth_fast_start")
}

internal suspend fun awaitAuthHandshakeState(
    publicKey: String,
    privateKeyHash: String,
    attempts: Int = 2,
    timeoutMs: Long = 25_000L
): ProtocolState? {
    repeat(attempts) { attempt ->
        startAuthHandshakeFast(publicKey, privateKeyHash)

        val state = withTimeoutOrNull(timeoutMs) {
            ProtocolManager.state.first {
                it == ProtocolState.AUTHENTICATED ||
                    it == ProtocolState.DEVICE_VERIFICATION_REQUIRED
            }
        }
        if (state != null) {
            return state
        }
        ProtocolManager.reconnectNowIfNeeded("auth_handshake_retry_${attempt + 1}")
    }
    return null
}
