package p2p

import (
	"net"
	"sync"
	"time"

	"github.com/libp2p/go-libp2p/core/network"
)

const (
	MaxConnsPerIP   = 5
	MinReconnectGap = 10 * time.Second
)

var (
	ipConnCount   = make(map[string]int)
	peerLastSeen  = make(map[string]time.Time)
	limiterMu     sync.Mutex
)

// LimitConnections implementa proteção básica anti-DDoS/Sybil
func LimitConnections(conn network.Conn) error {
	limiterMu.Lock()
	defer limiterMu.Unlock()

	ip, _, err := net.SplitHostPort(conn.RemoteMultiaddr().String())
	if err != nil {
		return nil // fallback: não bloqueia
	}

	ipConnCount[ip]++
	if ipConnCount[ip] > MaxConnsPerIP {
		return network.ErrReset
	}

	peerID := conn.RemotePeer().String()
	last := peerLastSeen[peerID]
	if time.Since(last) < MinReconnectGap {
		return network.ErrReset
	}
	peerLastSeen[peerID] = time.Now()

	return nil
}

// ClearConnection cleanup quando o peer desconecta
func ClearConnection(conn network.Conn) {
	limiterMu.Lock()
	defer limiterMu.Unlock()
	ip, _, err := net.SplitHostPort(conn.RemoteMultiaddr().String())
	if err == nil {
		ipConnCount[ip]--
		if ipConnCount[ip] <= 0 {
			delete(ipConnCount, ip)
		}
	}
}