package api

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

	"gitea.mrixs.me/minecraft-platform/backend/internal/core"
	"gitea.mrixs.me/minecraft-platform/backend/internal/database"
	"gitea.mrixs.me/minecraft-platform/backend/internal/models"
	"gitea.mrixs.me/minecraft-platform/backend/internal/utils"
	"github.com/golang-jwt/jwt/v5"
)

type UserHandler struct {
	Service *core.UserService
}

func (h *UserHandler) Register(w http.ResponseWriter, r *http.Request) {
	var req models.RegisterRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	if validationErrors := utils.ValidateStruct(req); validationErrors != nil {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(validationErrors)
		return
	}

	slog.Info("Received registration request", "username", req.Username, "email", req.Email)

	err := h.Service.RegisterNewUser(r.Context(), req)
	if err != nil {
		slog.Error("Service returned error", "error", err)

		switch {
		case errors.Is(err, database.ErrUserExists):
			http.Error(w, err.Error(), http.StatusConflict)
		case errors.Is(err, core.ErrInvalidUsername), errors.Is(err, core.ErrInvalidEmail), errors.Is(err, core.ErrPasswordTooShort):
			http.Error(w, err.Error(), http.StatusBadRequest)
		default:
			http.Error(w, "Internal server error", http.StatusInternalServerError)
		}
		return
	}

	slog.Info("User registered successfully", "username", req.Username)
	w.WriteHeader(http.StatusCreated)
}

// GetMe возвращает информацию о текущем аутентифицированном пользователе
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
	claims, ok := r.Context().Value(ClaimsContextKey).(jwt.MapClaims)
	if !ok {
		http.Error(w, "Could not get claims from context", http.StatusInternalServerError)
		return
	}

	// В AuthMiddleware мы не проверяли тип user_id, там json.Number или float64
	// Обычно jwt-go возвращает float64
	var userID int
	if idFloat, ok := claims["user_id"].(float64); ok {
		userID = int(idFloat)
	} else {
		log.Printf("[Handler] Invalid user_id type in claims: %T", claims["user_id"])
		http.Error(w, "Invalid token claims", http.StatusUnauthorized)
		return
	}

	user, err := h.Service.GetUserByID(r.Context(), userID)
	if err != nil {
		log.Printf("[Handler] Failed to get user by ID: %v", err)
		http.Error(w, "User not found", http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(user)
}
