package peer

import (
	"encoding/json"
	"log"
	"net"
	"net/http"
	"net/netip"
	"os"
)

type StatusReport struct {
	Network     []byte
	RelayPeerIP byte
	Remotes     []RemoteStatus
}

type RemoteStatus struct {
	PeerIP     byte
	Up         bool
	Name       string
	PublicIP   []byte
	Port       uint16
	Relay      bool
	Server     bool
	Direct     bool
	DirectAddr netip.AddrPort
}

func runStatusServer(g Globals, socketPath string) {
	_ = os.RemoveAll(socketPath)

	handler := func(w http.ResponseWriter, r *http.Request) {
		report := StatusReport{
			Network: g.Network,
			Remotes: make([]RemoteStatus, 0, 255),
		}

		relayStatus, ok := g.RelayHandler.Load().Status()
		if ok {
			report.RelayPeerIP = relayStatus.PeerIP
		}

		for i := range g.RemotePeers {
			remote := g.RemotePeers[i].Load()
			status, ok := remote.Status()
			if !ok {
				continue
			}
			report.Remotes = append(report.Remotes, status)
		}

		json.NewEncoder(w).Encode(report)
	}

	server := http.Server{
		Handler: http.HandlerFunc(handler),
	}

	unixListener, err := net.Listen("unix", socketPath)
	if err != nil {
		log.Fatalf("Failed to bind to unix socket: %v", err)
	}
	if err := server.Serve(unixListener); err != nil {
		log.Fatalf("Failed to serve on unix socket: %v", err)
	}
}
