package server

import (
	"net/http"
	"strconv"

	"github.com/go-chi/chi/v5"

	"github.com/operator/command-center/internal/budgets"
)

// BudgetsDeps wraps the Phase 10 tracker.
type BudgetsDeps struct {
	Tracker *budgets.Tracker
}

func (s *Server) handleListBudgets(w http.ResponseWriter, r *http.Request) {
	if s.budgets == nil {
		http.Error(w, "budgets not configured", http.StatusServiceUnavailable)
		return
	}
	states, err := s.budgets.Tracker.CurrentStates(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"count": len(states), "states": states})
}

func (s *Server) handleBudgetState(w http.ResponseWriter, r *http.Request) {
	if s.budgets == nil {
		http.Error(w, "budgets not configured", http.StatusServiceUnavailable)
		return
	}
	name := chi.URLParam(r, "name")
	states, err := s.budgets.Tracker.CurrentStates(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	for _, s := range states {
		if s.BudgetName == name {
			writeJSON(w, http.StatusOK, s)
			return
		}
	}
	http.Error(w, "not found", http.StatusNotFound)
}

func (s *Server) handleBudgetHistory(w http.ResponseWriter, r *http.Request) {
	if s.budgets == nil {
		http.Error(w, "budgets not configured", http.StatusServiceUnavailable)
		return
	}
	name := chi.URLParam(r, "name")
	limit := 12
	if v := r.URL.Query().Get("limit"); v != "" {
		if n, _ := strconv.Atoi(v); n > 0 {
			limit = n
		}
	}
	out, err := s.budgets.Tracker.History(r.Context(), name, limit)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"name": name, "count": len(out), "history": out})
}
