package bridge

import (
	"crypto/tls"
	"net"
	"time"

	"github.com/xtaci/smux"
)

const (
	// HeartbeatInterval is the application-level ping interval (agent and server probe).
	HeartbeatInterval = 30 * time.Second
	// HeartbeatTimeout evicts a session when no ping/pong for this duration.
	HeartbeatTimeout = 90 * time.Second
	// WatchdogInterval is how often the server checks agent heartbeats.
	WatchdogInterval = 15 * time.Second
	// ServerProbeAfter triggers a server-initiated ping when agent has been silent.
	ServerProbeAfter = 45 * time.Second
)

func SmuxConfig() *smux.Config {
	return smuxConfig()
}

func smuxConfig() *smux.Config {
	cfg := smux.DefaultConfig()
	cfg.KeepAliveInterval = 10 * time.Second
	cfg.KeepAliveTimeout = 30 * time.Second
	return cfg
}

func SetTCPKeepAlive(conn net.Conn) {
	for {
		switch c := conn.(type) {
		case *net.TCPConn:
			_ = c.SetKeepAlive(true)
			_ = c.SetKeepAlivePeriod(30 * time.Second)
			return
		case *tls.Conn:
			conn = c.NetConn()
		default:
			return
		}
	}
}
