package api

import (
	"encoding/json"
	"errors"
	"net/http"

	"gitea.mrixs.me/minecraft-platform/backend/internal/core"
	"gitea.mrixs.me/minecraft-platform/backend/internal/database"
	"github.com/go-chi/chi/v5"
	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
)

type ProfileHandler struct {
	Service *core.ProfileService
}

func (h *ProfileHandler) GetProfile(w http.ResponseWriter, r *http.Request) {
	playerUUIDStr := chi.URLParam(r, "uuid")
	playerUUID, err := uuid.Parse(playerUUIDStr)
	if err != nil {
		http.Error(w, "Invalid UUID format", http.StatusBadRequest)
		return
	}

	profile, err := h.Service.GetSignedProfile(r.Context(), playerUUID)
	if err != nil {
		if errors.Is(err, database.ErrUserNotFound) {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(profile)
}

func (h *ProfileHandler) UploadSkin(w http.ResponseWriter, r *http.Request) {
	// Получаем claims из контекста
	claims, ok := r.Context().Value(ClaimsContextKey).(jwt.MapClaims)
	if !ok {
		http.Error(w, "Could not get claims from context", http.StatusInternalServerError)
		return
	}
	userIDFloat, ok := claims["user_id"].(float64)
	if !ok {
		http.Error(w, "Invalid user_id in token", http.StatusInternalServerError)
		return
	}
	userID := int(userIDFloat)

	r.ParseMultipartForm(256 << 10) // 256KB

	file, header, err := r.FormFile("skin")
	if err != nil {
		http.Error(w, "Invalid file upload", http.StatusBadRequest)
		return
	}
	defer file.Close()

	err = h.Service.UpdateUserSkin(r.Context(), userID, file, header)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("Skin updated successfully"))
}
