package handlers

import (
	"net/http"
	"strconv"

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

type HomeHandler struct {
	homeService *service.HomeService
}

func NewHomeHandler(homeService *service.HomeService) *HomeHandler {
	return &HomeHandler{homeService: homeService}
}

func (h *HomeHandler) GetHome(w http.ResponseWriter, r *http.Request) {
	result, err := h.homeService.GetHome(r.Context(), buildListCardsInput(r))
	if err != nil {
		httpx.WriteError(w, err)
		return
	}
	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}

func (h *HomeHandler) GetCards(w http.ResponseWriter, r *http.Request) {
	result, err := h.homeService.ListCards(r.Context(), buildListCardsInput(r))
	if err != nil {
		httpx.WriteError(w, err)
		return
	}
	httpx.WriteJSON(w, http.StatusOK, map[string]any{"data": result})
}

func buildListCardsInput(r *http.Request) service.ListCardsInput {
	limit := 20
	if raw := r.URL.Query().Get("limit"); raw != "" {
		if parsed, err := strconv.Atoi(raw); err == nil {
			limit = parsed
		}
	}

	return service.ListCardsInput{
		ChannelCode:   r.URL.Query().Get("channelCode"),
		ChannelType:   r.URL.Query().Get("channelType"),
		PlatformAppID: r.URL.Query().Get("platformAppId"),
		TenantCode:    r.URL.Query().Get("tenantCode"),
		Slot:          r.URL.Query().Get("slot"),
		Limit:         limit,
	}
}
