package server

import (
	"net/http"

	"galaxy/backend/internal/lobby"
	"galaxy/backend/internal/server/handlers"
	"galaxy/backend/internal/server/httperr"
	"galaxy/backend/internal/server/middleware/userid"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// UserLobbyRaceNamesHandlers groups the race-name-directory handlers
// under `/api/v1/user/lobby/race-names/*`. The current implementation ships real
// implementations backed by `*lobby.Service`.
type UserLobbyRaceNamesHandlers struct {
	svc *lobby.Service
	logger *zap.Logger
}

// NewUserLobbyRaceNamesHandlers constructs the handler set. svc may be
// nil — in that case every handler returns 501 not_implemented.
func NewUserLobbyRaceNamesHandlers(svc *lobby.Service, logger *zap.Logger) *UserLobbyRaceNamesHandlers {
	if logger == nil {
		logger = zap.NewNop()
	}
	return &UserLobbyRaceNamesHandlers{svc: svc, logger: logger.Named("http.user.lobby.race_names")}
}

// Register handles POST /api/v1/user/lobby/race-names/register.
func (h *UserLobbyRaceNamesHandlers) Register() gin.HandlerFunc {
	if h.svc == nil {
		return handlers.NotImplemented("userLobbyRaceNamesRegister")
	}
	return func(c *gin.Context) {
		userID, ok := userid.FromContext(c.Request.Context())
		if !ok {
			httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "X-User-ID header is required")
			return
		}
		var req raceNameRegisterRequestWire
		if err := c.ShouldBindJSON(&req); err != nil {
			httperr.Abort(c, http.StatusBadRequest, httperr.CodeInvalidRequest, "request body must be valid JSON")
			return
		}
		ctx := c.Request.Context()
		entry, err := h.svc.RegisterRaceName(ctx, userID, req.Name)
		if err != nil {
			respondLobbyError(c, h.logger, "user lobby race-names register", ctx, err)
			return
		}
		c.JSON(http.StatusOK, raceNameDetailToWire(entry))
	}
}

// raceNameRegisterRequestWire mirrors `RaceNameRegisterRequest`.
type raceNameRegisterRequestWire struct {
	Name string `json:"name"`
}
