package roomapi

import (
	"context"
	"crypto/sha256"
	"encoding/binary"
	"fmt"
	"strings"

	"hyapp/services/gateway-service/internal/appconfig"
)

type giftComboConfigReader interface {
	GiftComboConfig(ctx context.Context, appCode string) (appconfig.GiftComboConfig, error)
}

// roomGiftComboConfig resolves rollout on the server so every device logged in as the same App user
// receives the same policy. The client does not need to reproduce a hashing algorithm or trust a
// locally generated random bucket across reinstallations.
func (h *Handler) roomGiftComboConfig(ctx context.Context, appCode string, userID int64) (appconfig.GiftComboConfig, error) {
	config := appconfig.DefaultGiftComboConfig()
	reader := h.giftComboReader
	if reader != nil {
		var err error
		config, err = reader.GiftComboConfig(ctx, appCode)
		if err != nil {
			return disabledGiftComboFallback(), err
		}
	}

	assigned := giftComboRolloutBucket(appCode, userID) < uint32(config.RolloutBasisPoints)
	// 灰度和 enabled 只控制客户端是否把连续点击合成微批；当前 Flutter 的账务入口始终是
	// /api/v2/rooms/gift/send。旧客户端是否使用 V1 由其已发布代码决定，不能通过面板配置
	// 把新客户端切回旧财务协议。
	config.Enabled = config.Enabled && assigned
	config.APIVersion = 2
	return config, nil
}

func disabledGiftComboFallback() appconfig.GiftComboConfig {
	config := appconfig.DefaultGiftComboConfig()
	config.Enabled = false
	// 配置读取失败只关闭微批，避免未知策略放大请求；接口版本仍固定为 V2。
	config.APIVersion = 2
	return config
}

func giftComboRolloutBucket(appCode string, userID int64) uint32 {
	identity := fmt.Sprintf("%s:%d", strings.ToLower(strings.TrimSpace(appCode)), userID)
	digest := sha256.Sum256([]byte(identity))
	return binary.BigEndian.Uint32(digest[:4]) % 10_000
}
