package com.rosetta.messenger.ui.auth

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

internal suspend fun awaitAuthHandshakeState(
    publicKey: String,
    privateKeyHash: String,
    attempts: Int = 2,
    timeoutMs: Long = 25_000L
): ProtocolState? {
    repeat(attempts) {
        ProtocolManager.disconnect()
        delay(200)
        ProtocolManager.authenticate(publicKey, privateKeyHash)

        val state = withTimeoutOrNull(timeoutMs) {
            ProtocolManager.state.first {
                it == ProtocolState.AUTHENTICATED ||
                    it == ProtocolState.DEVICE_VERIFICATION_REQUIRED
            }
        }
        if (state != null) {
            return state
        }
    }
    return null
}
