package httpapi

import (
	"log/slog"
	"net/http"

	"commilitia.net/cdrop/internal/calls"
)

// fallbackICEServers is what we return when Cloudflare is not configured or
// generation fails: STUN-only (Cloudflare anycast, China-friendly).
var fallbackICEServers = []calls.ICEServer{
	{URLs: []string{"stun:stun.cloudflare.com:3478"}},
}

// handleCallsCredentials returns ICE servers for the WebRTC client.
// Auth-required (don't expose Cloudflare creds to anonymous probes).
func (s *Server) handleCallsCredentials(w http.ResponseWriter, r *http.Request) {
	if s.calls == nil {
		writeJSON(w, http.StatusOK, map[string]any{"iceServers": fallbackICEServers})
		return
	}
	creds, err := s.calls.Get(r.Context())
	if err != nil {
		slog.Warn("cf turn credentials unavailable; serving fallback STUN", "err", err)
		writeJSON(w, http.StatusOK, map[string]any{"iceServers": fallbackICEServers})
		return
	}
	writeJSON(w, http.StatusOK, creds)
}
