package com.sshproxy.vpn.ssh

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Periodically verifies SSH session health while the tunnel is active.
 */
class ConnectionHealthMonitor(
    private val sshManager: SshTunnelManager,
    private val onConnectionLost: () -> Unit
) {
    private var job: Job? = null

    fun start(scope: CoroutineScope, intervalMs: Long = DEFAULT_INTERVAL_MS) {
        stop()
        job = scope.launch {
            while (isActive) {
                delay(intervalMs.coerceAtLeast(MIN_INTERVAL_MS))
                val healthy = withContext(Dispatchers.IO) { sshManager.checkHealth() }
                if (!healthy) {
                    withContext(Dispatchers.Main) {
                        onConnectionLost()
                    }
                    break
                }
            }
        }
    }

    fun stop() {
        job?.cancel()
        job = null
    }

    companion object {
        const val DEFAULT_INTERVAL_MS = 30_000L
        private const val MIN_INTERVAL_MS = 5_000L
    }
}
