package handler

import (
	"database/sql"
	"krafttrainer/internal/model"
	"net/http"
)

func (h *Handler) handleListExercises(w http.ResponseWriter, r *http.Request) {
	muscleGroup := r.URL.Query().Get("muscle_group")
	query := r.URL.Query().Get("q")

	exercises, err := h.store.ListExercises(muscleGroup, query)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Laden der Übungen")
		return
	}
	writeJSON(w, http.StatusOK, exercises)
}

func (h *Handler) handleCreateExercise(w http.ResponseWriter, r *http.Request) {
	var req model.CreateExerciseRequest
	if err := decodeJSON(r, &req); err != nil {
		writeError(w, http.StatusBadRequest, "Ungültiger Request-Body")
		return
	}
	if err := req.Validate(); err != nil {
		writeError(w, http.StatusBadRequest, err.Error())
		return
	}

	exercise, err := h.store.CreateExercise(&req)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Erstellen der Übung")
		return
	}
	writeJSON(w, http.StatusCreated, exercise)
}

func (h *Handler) handleUpdateExercise(w http.ResponseWriter, r *http.Request) {
	id, err := pathID(r, "id")
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungültige ID")
		return
	}

	var req model.CreateExerciseRequest
	if err := decodeJSON(r, &req); err != nil {
		writeError(w, http.StatusBadRequest, "Ungültiger Request-Body")
		return
	}
	if err := req.Validate(); err != nil {
		writeError(w, http.StatusBadRequest, err.Error())
		return
	}

	exercise, err := h.store.UpdateExercise(id, &req)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Aktualisieren der Übung")
		return
	}
	if exercise == nil {
		writeError(w, http.StatusNotFound, "Übung nicht gefunden")
		return
	}
	writeJSON(w, http.StatusOK, exercise)
}

func (h *Handler) handleDeleteExercise(w http.ResponseWriter, r *http.Request) {
	id, err := pathID(r, "id")
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungültige ID")
		return
	}

	err = h.store.SoftDeleteExercise(id)
	if err == sql.ErrNoRows {
		writeError(w, http.StatusNotFound, "Übung nicht gefunden")
		return
	}
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Löschen der Übung")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
