package monitor

import (
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
)

var (
	peers          = make(map[string]bool)
	peersLock      sync.RWMutex
	heartbeatFreq  = 3 * time.Second
)

func StartHeartbeatMonitor() {
	peerList := strings.Split(os.Getenv("DEJO_PEERS"), ",")
	for _, p := range peerList {
		peers[p] = false // Inicialmente offline
	}

	go func() {
		ticker := time.NewTicker(heartbeatFreq)
		for range ticker.C {
			checkPeers(peerList)
		}
	}()
}

func checkPeers(peerList []string) {
	for _, peer := range peerList {
		go func(p string) {
			resp, err := http.Get(p + "/ping")
			peersLock.Lock()
			defer peersLock.Unlock()
			if err != nil || resp.StatusCode != http.StatusOK {
				if peers[p] {
					log.Printf("⚠️ Peer %s está OFFLINE", p)
				}
				peers[p] = false
			} else {
				if !peers[p] {
					log.Printf("✅ Peer %s voltou ONLINE", p)
				}
				peers[p] = true
			}
		} (peer)
	}
}

func IsPeerOnline(peer string) bool {
	peersLock.RLock()
	defer peersLock.RUnlock()
	return peers[peer]
}