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 firstRechargeRewardTierData struct {
	TierID          int64  `json:"tier_id"`
	TierCode        string `json:"tier_code"`
	TierName        string `json:"tier_name"`
	MinCoinAmount   int64  `json:"min_coin_amount"`
	MaxCoinAmount   int64  `json:"max_coin_amount"`
	ResourceGroupID int64  `json:"resource_group_id"`
	Status          string `json:"status"`
	SortOrder       int32  `json:"sort_order"`
}

type firstRechargeRewardClaimData struct {
	ClaimID            string `json:"claim_id"`
	TransactionID      string `json:"transaction_id"`
	UserID             int64  `json:"user_id"`
	TierID             int64  `json:"tier_id"`
	TierCode           string `json:"tier_code"`
	ResourceGroupID    int64  `json:"resource_group_id"`
	RechargeCoinAmount int64  `json:"recharge_coin_amount"`
	RechargeSequence   int64  `json:"recharge_sequence"`
	RechargeType       string `json:"recharge_type"`
	Status             string `json:"status"`
	WalletGrantID      string `json:"wallet_grant_id"`
	FailureReason      string `json:"failure_reason"`
	RechargedAtMS      int64  `json:"recharged_at_ms"`
	GrantedAtMS        int64  `json:"granted_at_ms"`
	CreatedAtMS        int64  `json:"created_at_ms"`
	UpdatedAtMS        int64  `json:"updated_at_ms"`
}

type firstRechargeRewardStatusData struct {
	Enabled      bool                          `json:"enabled"`
	Tiers        []firstRechargeRewardTierData `json:"tiers"`
	Rewarded     bool                          `json:"rewarded"`
	Claim        *firstRechargeRewardClaimData `json:"claim,omitempty"`
	ServerTimeMS int64                         `json:"server_time_ms"`
}

func (h *Handler) getFirstRechargeRewardStatus(writer http.ResponseWriter, request *http.Request) {
	if h.firstRechargeReward == nil {
		httpkit.WriteError(writer, request, http.StatusBadGateway, httpkit.CodeUpstreamError, "upstream service error")
		return
	}
	resp, err := h.firstRechargeReward.GetFirstRechargeRewardStatus(request.Context(), &activityv1.GetFirstRechargeRewardStatusRequest{
		Meta:   httpkit.ActivityMeta(request),
		UserId: auth.UserIDFromContext(request.Context()),
	})
	if err != nil {
		httpkit.WriteRPCError(writer, request, err)
		return
	}
	httpkit.WriteOK(writer, request, firstRechargeRewardStatusFromProto(resp.GetStatus()))
}

func firstRechargeRewardStatusFromProto(item *activityv1.FirstRechargeRewardStatus) firstRechargeRewardStatusData {
	if item == nil {
		return firstRechargeRewardStatusData{Tiers: []firstRechargeRewardTierData{}}
	}
	tiers := make([]firstRechargeRewardTierData, 0, len(item.GetTiers()))
	for _, tier := range item.GetTiers() {
		tiers = append(tiers, firstRechargeRewardTierFromProto(tier))
	}
	var claim *firstRechargeRewardClaimData
	if item.GetClaim() != nil {
		converted := firstRechargeRewardClaimFromProto(item.GetClaim())
		claim = &converted
	}
	return firstRechargeRewardStatusData{
		Enabled:      item.GetEnabled(),
		Tiers:        tiers,
		Rewarded:     item.GetRewarded(),
		Claim:        claim,
		ServerTimeMS: item.GetServerTimeMs(),
	}
}

func firstRechargeRewardTierFromProto(item *activityv1.FirstRechargeRewardTier) firstRechargeRewardTierData {
	if item == nil {
		return firstRechargeRewardTierData{}
	}
	return firstRechargeRewardTierData{
		TierID:          item.GetTierId(),
		TierCode:        item.GetTierCode(),
		TierName:        item.GetTierName(),
		MinCoinAmount:   item.GetMinCoinAmount(),
		MaxCoinAmount:   item.GetMaxCoinAmount(),
		ResourceGroupID: item.GetResourceGroupId(),
		Status:          item.GetStatus(),
		SortOrder:       item.GetSortOrder(),
	}
}

func firstRechargeRewardClaimFromProto(item *activityv1.FirstRechargeRewardClaim) firstRechargeRewardClaimData {
	if item == nil {
		return firstRechargeRewardClaimData{}
	}
	return firstRechargeRewardClaimData{
		ClaimID:            item.GetClaimId(),
		TransactionID:      item.GetTransactionId(),
		UserID:             item.GetUserId(),
		TierID:             item.GetTierId(),
		TierCode:           item.GetTierCode(),
		ResourceGroupID:    item.GetResourceGroupId(),
		RechargeCoinAmount: item.GetRechargeCoinAmount(),
		RechargeSequence:   item.GetRechargeSequence(),
		RechargeType:       item.GetRechargeType(),
		Status:             item.GetStatus(),
		WalletGrantID:      item.GetWalletGrantId(),
		FailureReason:      item.GetFailureReason(),
		RechargedAtMS:      item.GetRechargedAtMs(),
		GrantedAtMS:        item.GetGrantedAtMs(),
		CreatedAtMS:        item.GetCreatedAtMs(),
		UpdatedAtMS:        item.GetUpdatedAtMs(),
	}
}
