package handler

import (
	"encoding/json"
	"krafttrainer/internal/store"
	"net/http"
	"strconv"
)

// Handler bündelt alle HTTP-Handler und hält eine Referenz auf den Store.
type Handler struct {
	store *store.Store
}

// New erstellt einen neuen Handler.
func New(store *store.Store) *Handler {
	return &Handler{store: store}
}

// RegisterRoutes registriert alle API-Routen am ServeMux.
func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
	// Exercises
	mux.HandleFunc("GET /api/v1/exercises", h.handleListExercises)
	mux.HandleFunc("POST /api/v1/exercises", h.handleCreateExercise)
	mux.HandleFunc("PUT /api/v1/exercises/{id}", h.handleUpdateExercise)
	mux.HandleFunc("DELETE /api/v1/exercises/{id}", h.handleDeleteExercise)

	// Training Sets
	mux.HandleFunc("GET /api/v1/sets", h.handleListSets)
	mux.HandleFunc("POST /api/v1/sets", h.handleCreateSet)
	mux.HandleFunc("PUT /api/v1/sets/{id}", h.handleUpdateSet)
	mux.HandleFunc("DELETE /api/v1/sets/{id}", h.handleDeleteSet)

	// Sessions
	mux.HandleFunc("POST /api/v1/sessions", h.handleCreateSession)
	mux.HandleFunc("GET /api/v1/sessions", h.handleListSessions)
	mux.HandleFunc("GET /api/v1/sessions/{id}", h.handleGetSession)
	mux.HandleFunc("PUT /api/v1/sessions/{id}/end", h.handleEndSession)

	// Session Logs
	mux.HandleFunc("POST /api/v1/sessions/{id}/logs", h.handleCreateLog)
	mux.HandleFunc("PUT /api/v1/sessions/{id}/logs/{logId}", h.handleUpdateLog)
	mux.HandleFunc("DELETE /api/v1/sessions/{id}/logs/{logId}", h.handleDeleteLog)

	// Stats
	mux.HandleFunc("GET /api/v1/exercises/{id}/last-log", h.handleGetLastLog)
	mux.HandleFunc("GET /api/v1/exercises/{id}/history", h.handleGetExerciseHistory)
	mux.HandleFunc("GET /api/v1/stats/overview", h.handleGetStatsOverview)
}

// --- Hilfsfunktionen ---

func writeJSON(w http.ResponseWriter, status int, data any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(data)
}

func writeError(w http.ResponseWriter, status int, message string) {
	writeJSON(w, status, map[string]string{"error": message})
}

func decodeJSON(r *http.Request, dst any) error {
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	return dec.Decode(dst)
}

func pathID(r *http.Request, name string) (int64, error) {
	return strconv.ParseInt(r.PathValue(name), 10, 64)
}

func queryInt(r *http.Request, name string, defaultVal int) int {
	v := r.URL.Query().Get(name)
	if v == "" {
		return defaultVal
	}
	n, err := strconv.Atoi(v)
	if err != nil {
		return defaultVal
	}
	return n
}
