package handler

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

func (h *Handler) handleCreateSession(w http.ResponseWriter, r *http.Request) {
	var req model.CreateSessionRequest
	if err := decodeJSON(r, &req); err != nil {
		writeError(w, http.StatusBadRequest, "Ungültiger Request-Body")
		return
	}
	if req.SetID == 0 {
		writeError(w, http.StatusBadRequest, "set_id ist erforderlich")
		return
	}

	session, err := h.store.CreateSession(req.SetID)
	if err != nil {
		if strings.Contains(err.Error(), "existiert nicht") {
			writeError(w, http.StatusBadRequest, err.Error())
			return
		}
		writeError(w, http.StatusInternalServerError, "Fehler beim Starten der Session")
		return
	}
	writeJSON(w, http.StatusCreated, session)
}

func (h *Handler) handleListSessions(w http.ResponseWriter, r *http.Request) {
	limit := queryInt(r, "limit", 20)
	offset := queryInt(r, "offset", 0)

	sessions, err := h.store.ListSessions(limit, offset)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Laden der Sessions")
		return
	}
	writeJSON(w, http.StatusOK, sessions)
}

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

	session, err := h.store.GetSession(id)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Laden der Session")
		return
	}
	if session == nil {
		writeError(w, http.StatusNotFound, "Session nicht gefunden")
		return
	}
	writeJSON(w, http.StatusOK, session)
}

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

	var body struct {
		Note string `json:"note"`
	}
	// Body ist optional
	decodeJSON(r, &body)

	session, err := h.store.EndSession(id, body.Note)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Beenden der Session")
		return
	}
	if session == nil {
		writeError(w, http.StatusNotFound, "Session nicht gefunden oder bereits beendet")
		return
	}
	writeJSON(w, http.StatusOK, session)
}

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

	var req model.CreateLogRequest
	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
	}

	log, err := h.store.CreateLog(sessionID, &req)
	if err != nil {
		if strings.Contains(err.Error(), "SESSION_CLOSED") {
			writeError(w, http.StatusBadRequest, "Session ist bereits beendet")
			return
		}
		if strings.Contains(err.Error(), "UNIQUE_VIOLATION") {
			writeError(w, http.StatusConflict, err.Error())
			return
		}
		if strings.Contains(err.Error(), "existiert nicht") {
			writeError(w, http.StatusBadRequest, err.Error())
			return
		}
		writeError(w, http.StatusInternalServerError, "Fehler beim Loggen des Satzes")
		return
	}
	writeJSON(w, http.StatusCreated, log)
}

func (h *Handler) handleUpdateLog(w http.ResponseWriter, r *http.Request) {
	sessionID, err := pathID(r, "id")
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungültige Session-ID")
		return
	}
	logID, err := pathID(r, "logId")
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungültige Log-ID")
		return
	}

	var req model.UpdateLogRequest
	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
	}

	log, err := h.store.UpdateLog(sessionID, logID, &req)
	if err != nil {
		if strings.Contains(err.Error(), "SESSION_CLOSED") {
			writeError(w, http.StatusBadRequest, "Session ist bereits beendet")
			return
		}
		writeError(w, http.StatusInternalServerError, "Fehler beim Aktualisieren des Satzes")
		return
	}
	if log == nil {
		writeError(w, http.StatusNotFound, "Log nicht gefunden")
		return
	}
	writeJSON(w, http.StatusOK, log)
}

func (h *Handler) handleDeleteLog(w http.ResponseWriter, r *http.Request) {
	sessionID, err := pathID(r, "id")
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungültige Session-ID")
		return
	}
	logID, err := pathID(r, "logId")
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungültige Log-ID")
		return
	}

	err = h.store.DeleteLog(sessionID, logID)
	if err != nil {
		if strings.Contains(err.Error(), "SESSION_CLOSED") {
			writeError(w, http.StatusBadRequest, "Session ist bereits beendet")
			return
		}
		if err == sql.ErrNoRows {
			writeError(w, http.StatusNotFound, "Log nicht gefunden")
			return
		}
		writeError(w, http.StatusInternalServerError, "Fehler beim Löschen des Satzes")
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
