package webrtc

import "fmt"

// PortRange represents an inclusive UDP port range.
type PortRange struct {
	Low, High int
}

// Config controls the WebRTC egress module.
type Config struct {
	// Enabled toggles the entire module. When false, no endpoints are served.
	Enabled bool

	// WHEPListen is the address the WHEP HTTP endpoint binds to (e.g. ":8787").
	WHEPListen string

	// PublicIP is the server's externally-reachable IP, advertised in ICE
	// candidates via NAT1To1. Empty means rely on STUN discovery.
	PublicIP string

	// UDPPortRange bounds the local UDP ports allocated for FFmpeg→Pion RTP.
	UDPPortRange PortRange

	// ICEServers is the list of STUN/TURN URIs given to each PeerConnection.
	ICEServers []string

	// MaxPeersTotal is a hard safety cap on concurrent subscribers.
	MaxPeersTotal int
}

// DefaultConfig returns production-reasonable defaults.
func DefaultConfig() Config {
	return Config{
		Enabled:       true,
		WHEPListen:    ":8787",
		PublicIP:      "",
		UDPPortRange:  PortRange{Low: 10000, High: 10100},
		ICEServers:    []string{"stun:stun.cloudflare.com:3478", "stun:stun.l.google.com:19302"},
		MaxPeersTotal: 32,
	}
}

// Validate returns an error if the config is internally inconsistent.
func (c Config) Validate() error {
	if c.WHEPListen == "" {
		return fmt.Errorf("webrtc: WHEPListen must not be empty")
	}
	if c.UDPPortRange.Low <= 0 || c.UDPPortRange.High <= 0 {
		return fmt.Errorf("webrtc: UDPPortRange must have positive bounds, got %v", c.UDPPortRange)
	}
	if c.UDPPortRange.Low > c.UDPPortRange.High {
		return fmt.Errorf("webrtc: UDPPortRange.Low > High (%d > %d)", c.UDPPortRange.Low, c.UDPPortRange.High)
	}
	if c.MaxPeersTotal <= 0 {
		return fmt.Errorf("webrtc: MaxPeersTotal must be positive, got %d", c.MaxPeersTotal)
	}
	return nil
}
