package handler

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

func (h *Handler) handleListSets(w http.ResponseWriter, r *http.Request) {
	sets, err := h.store.ListSets()
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Laden der Sets")
		return
	}
	writeJSON(w, http.StatusOK, sets)
}

func (h *Handler) handleCreateSet(w http.ResponseWriter, r *http.Request) {
	var req model.CreateSetRequest
	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
	}

	set, err := h.store.CreateSet(&req)
	if err != nil {
		if strings.Contains(err.Error(), "existiert nicht") {
			writeError(w, http.StatusBadRequest, err.Error())
			return
		}
		writeError(w, http.StatusInternalServerError, "Fehler beim Erstellen des Sets")
		return
	}
	writeJSON(w, http.StatusCreated, set)
}

func (h *Handler) handleUpdateSet(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.UpdateSetRequest
	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
	}

	set, err := h.store.UpdateSet(id, &req)
	if err != nil {
		if strings.Contains(err.Error(), "existiert nicht") {
			writeError(w, http.StatusBadRequest, err.Error())
			return
		}
		writeError(w, http.StatusInternalServerError, "Fehler beim Aktualisieren des Sets")
		return
	}
	if set == nil {
		writeError(w, http.StatusNotFound, "Set nicht gefunden")
		return
	}
	writeJSON(w, http.StatusOK, set)
}

func (h *Handler) handleDeleteSet(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.SoftDeleteSet(id)
	if err == sql.ErrNoRows {
		writeError(w, http.StatusNotFound, "Set nicht gefunden")
		return
	}
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Löschen des Sets")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
