package activityapi

import (
	"net/http"

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

type registrationRewardEligibilityData struct {
	CanReceive      bool   `json:"can_receive"`
	Reason          string `json:"reason"`
	Enabled         bool   `json:"enabled"`
	RewardType      string `json:"reward_type"`
	CoinAmount      int64  `json:"coin_amount"`
	ResourceGroupID int64  `json:"resource_group_id"`
	DailyLimit      int64  `json:"daily_limit"`
	DailyUsed       int64  `json:"daily_used"`
	DailyRemaining  int64  `json:"daily_remaining"`
	RewardDay       string `json:"reward_day"`
	ServerTimeMS    int64  `json:"server_time_ms"`
}

// getRegistrationRewardEligibility 只查询资格，不执行发放；注册后的实际发放由 user-service 触发。
func (h *Handler) getRegistrationRewardEligibility(writer http.ResponseWriter, request *http.Request) {
	if h.registrationReward == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}
	resp, err := h.registrationReward.GetRegistrationRewardEligibility(request.Context(), &activityv1.GetRegistrationRewardEligibilityRequest{
		Meta:   httpkit.ActivityMeta(request),
		UserId: auth.UserIDFromContext(request.Context()),
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	httpkit.WriteOK(writer, request, registrationRewardEligibilityFromProto(resp.GetEligibility()))
}

func registrationRewardEligibilityFromProto(item *activityv1.RegistrationRewardEligibility) registrationRewardEligibilityData {
	if item == nil {
		return registrationRewardEligibilityData{}
	}
	return registrationRewardEligibilityData{
		CanReceive:      item.GetCanReceive(),
		Reason:          item.GetReason(),
		Enabled:         item.GetEnabled(),
		RewardType:      item.GetRewardType(),
		CoinAmount:      item.GetCoinAmount(),
		ResourceGroupID: item.GetResourceGroupId(),
		DailyLimit:      item.GetDailyLimit(),
		DailyUsed:       item.GetDailyUsed(),
		DailyRemaining:  item.GetDailyRemaining(),
		RewardDay:       item.GetRewardDay(),
		ServerTimeMS:    item.GetServerTimeMs(),
	}
}
