package activityapi

import (
	"encoding/json"
	"net/http"
	"strings"

	luckygiftv1 "hyapp.local/api/proto/luckygift/v1"
	"hyapp/services/gateway-service/internal/auth"
	"hyapp/services/gateway-service/internal/transport/http/httpkit"
)

type luckyGiftCheckRequest struct {
	RoomID string `json:"room_id"`
	GiftID string `json:"gift_id"`
	PoolID string `json:"pool_id"`
}

type luckyGiftCheckData struct {
	Enabled        bool   `json:"enabled"`
	Reason         string `json:"reason"`
	RoomID         string `json:"room_id"`
	GiftID         string `json:"gift_id"`
	PoolID         string `json:"pool_id"`
	GiftPrice      int64  `json:"gift_price"`
	RuleVersion    int64  `json:"rule_version"`
	TargetRTPPPM   int64  `json:"target_rtp_ppm"`
	ExperiencePool string `json:"experience_pool"`
}

// checkLuckyGift 只做送礼前资格检查；扣费、抽奖和返奖都必须继续走 room-service 送礼主链路。
func (h *Handler) checkLuckyGift(writer http.ResponseWriter, request *http.Request) {
	if h.luckyGift == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}
	var body luckyGiftCheckRequest
	if err := json.NewDecoder(request.Body).Decode(&body); err != nil {
		httpkit.WriteError(writer, request, http.StatusBadRequest, httpkit.CodeInvalidArgument, "invalid request body")
		return
	}
	body.RoomID = strings.TrimSpace(body.RoomID)
	body.GiftID = strings.TrimSpace(body.GiftID)
	body.PoolID = strings.TrimSpace(body.PoolID)
	if body.RoomID == "" || body.GiftID == "" || body.PoolID == "" {
		httpkit.WriteError(writer, request, http.StatusBadRequest, httpkit.CodeInvalidArgument, "room_id, gift_id and pool_id are required")
		return
	}
	resp, err := h.luckyGift.CheckLuckyGift(request.Context(), &luckygiftv1.CheckLuckyGiftRequest{
		// gateway 只做送礼前协议适配；资格、规则版本和奖池判断统一交给 lucky-gift-service，
		// 避免 activity-service 继续持有旧 owner 逻辑，也避免 HTTP 层复制风控/RTP 边界。
		Meta:     httpkit.LuckyGiftMeta(request),
		UserId:   auth.UserIDFromContext(request.Context()),
		DeviceId: auth.DeviceIDFromContext(request.Context()),
		RoomId:   body.RoomID,
		GiftId:   body.GiftID,
		PoolId:   body.PoolID,
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	httpkit.WriteOK(writer, request, luckyGiftCheckData{
		Enabled:        resp.GetEnabled(),
		Reason:         resp.GetReason(),
		RoomID:         body.RoomID,
		GiftID:         resp.GetGiftId(),
		PoolID:         resp.GetPoolId(),
		GiftPrice:      resp.GetGiftPrice(),
		RuleVersion:    resp.GetRuleVersion(),
		TargetRTPPPM:   resp.GetTargetRtpPpm(),
		ExperiencePool: resp.GetExperiencePool(),
	})
}
