package handlers

import (
	"net/http"
	"strconv"

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

type ResultHandler struct {
	resultService *service.ResultService
}

func NewResultHandler(resultService *service.ResultService) *ResultHandler {
	return &ResultHandler{resultService: resultService}
}

func (h *ResultHandler) GetSessionResult(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
	}

	result, err := h.resultService.GetSessionResult(r.Context(), r.PathValue("sessionPublicID"), auth.UserID)
	if err != nil {
		httpx.WriteError(w, err)
		return
	}

	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}

func (h *ResultHandler) ListMine(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
	}

	limit := 20
	if raw := r.URL.Query().Get("limit"); raw != "" {
		if parsed, err := strconv.Atoi(raw); err == nil {
			limit = parsed
		}
	}

	result, err := h.resultService.ListMyResults(r.Context(), auth.UserID, limit)
	if err != nil {
		httpx.WriteError(w, err)
		return
	}

	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}
