package handlers

import (
	"net/http"

	"cmr-backend/internal/apperr"
	"cmr-backend/internal/httpapi/middleware"
	"cmr-backend/internal/httpx"
	"cmr-backend/internal/service"
)

type EventHandler struct {
	eventService *service.EventService
}

func NewEventHandler(eventService *service.EventService) *EventHandler {
	return &EventHandler{eventService: eventService}
}

func (h *EventHandler) GetDetail(w http.ResponseWriter, r *http.Request) {
	eventPublicID := r.PathValue("eventPublicID")
	result, err := h.eventService.GetEventDetail(r.Context(), eventPublicID)
	if err != nil {
		httpx.WriteError(w, err)
		return
	}
	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}

func (h *EventHandler) Launch(w http.ResponseWriter, r *http.Request) {
	auth := middleware.GetAuthContext(r.Context())
	if auth == nil {
		httpx.WriteError(w, apperr.New(http.StatusUnauthorized, "unauthorized", "missing auth context"))
		return
	}

	var req service.LaunchEventInput
	if err := httpx.DecodeJSON(r, &req); err != nil {
		httpx.WriteError(w, apperr.New(http.StatusBadRequest, "invalid_json", "invalid request body"))
		return
	}
	req.EventPublicID = r.PathValue("eventPublicID")
	req.UserID = auth.UserID

	result, err := h.eventService.LaunchEvent(r.Context(), req)
	if err != nil {
		httpx.WriteError(w, err)
		return
	}
	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}
