package handlers

import (
	"net/http"
	"strconv"

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

type PublicExperienceHandler struct {
	service *service.PublicExperienceService
}

func NewPublicExperienceHandler(service *service.PublicExperienceService) *PublicExperienceHandler {
	return &PublicExperienceHandler{service: service}
}

func (h *PublicExperienceHandler) ListMaps(w http.ResponseWriter, r *http.Request) {
	limit := 20
	if raw := r.URL.Query().Get("limit"); raw != "" {
		if parsed, err := strconv.Atoi(raw); err == nil {
			limit = parsed
		}
	}
	result, err := h.service.ListMaps(r.Context(), service.ListExperienceMapsInput{Limit: limit})
	if err != nil {
		httpx.WriteError(w, err)
		return
	}
	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}

func (h *PublicExperienceHandler) GetMapDetail(w http.ResponseWriter, r *http.Request) {
	result, err := h.service.GetMapDetail(r.Context(), r.PathValue("mapAssetPublicID"))
	if err != nil {
		httpx.WriteError(w, err)
		return
	}
	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}

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

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

func (h *PublicExperienceHandler) Launch(w http.ResponseWriter, r *http.Request) {
	var req service.PublicLaunchEventInput
	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")

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