package api import ( "encoding/json" "nerd-monitor/internal/stats" "nerd-monitor/internal/store" "net/http" ) // Handler manages HTTP requests. type Handler struct { store *store.Store } // New creates a new API handler. func New(s *store.Store) *Handler { return &Handler{store: s} } // ReportStats handles agent stats reports. func (h *Handler) ReportStats(w http.ResponseWriter, r *http.Request) { agentID := r.URL.Query().Get("id") if agentID == "" { http.Error(w, "missing agent id", http.StatusBadRequest) return } var stat stats.Stats if err := json.NewDecoder(r.Body).Decode(&stat); err != nil { http.Error(w, "invalid request body", http.StatusBadRequest) return } h.store.UpdateAgent(agentID, &stat) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "ok"}) } // GetAgent returns stats for a single agent. func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) { agentID := r.URL.Query().Get("id") if agentID == "" { http.Error(w, "missing agent id", http.StatusBadRequest) return } agent := h.store.GetAgent(agentID) if agent == nil { http.Error(w, "agent not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(agent) } // ListAgents returns all agents. func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) { agents := h.store.GetAllAgents() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(agents) } // DeleteAgent removes an agent. func (h *Handler) DeleteAgent(w http.ResponseWriter, r *http.Request) { agentID := r.URL.Query().Get("id") if agentID == "" { http.Error(w, "missing agent id", http.StatusBadRequest) return } h.store.DeleteAgent(agentID) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "deleted"}) } // UpdateHostname updates the hostname for an agent. func (h *Handler) UpdateHostname(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } agentID := r.PathValue("id") if agentID == "" { http.Error(w, "missing agent id", http.StatusBadRequest) return } hostname := r.FormValue("hostname") if hostname == "" { http.Error(w, "missing hostname", http.StatusBadRequest) return } err := h.store.UpdateHostname(agentID, hostname) if err != nil { http.Error(w, "agent not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "updated"}) }