package com.rosetta.messenger.ui.auth

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

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

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

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