package app

import (
	"testing"

	"hyapp/pkg/walletmq"
	firstrechargedomain "hyapp/services/activity-service/internal/domain/firstrecharge"
)

func TestFirstRechargeEventFromWalletMessageSkipsNonGoogleRecharge(t *testing.T) {
	// 币商充值是合法钱包事实，但它没有 Google 商品 ID；首充 consumer 必须确认后跳过，避免 MQ 持续重投。
	body, err := walletmq.EncodeWalletOutboxMessage(walletmq.WalletOutboxMessage{
		AppCode:        "lalu",
		EventID:        "wev-coin-seller",
		EventType:      firstrechargedomain.RechargeEventWalletRecorded,
		TransactionID:  "wtx-coin-seller",
		CommandID:      "coin-seller-transfer-1",
		UserID:         42001,
		AssetType:      "COIN",
		AvailableDelta: 10000,
		PayloadJSON:    `{"recharge_type":"coin_seller_transfer","amount":10000,"recharge_sequence":1}`,
		OccurredAtMS:   1710000000000,
	})
	if err != nil {
		t.Fatalf("EncodeWalletOutboxMessage failed: %v", err)
	}

	event, ok, err := firstRechargeEventFromWalletMessage(body)
	if err != nil {
		t.Fatalf("firstRechargeEventFromWalletMessage returned error for non-google recharge: %v", err)
	}
	if ok || event.EventID != "" {
		t.Fatalf("non-google recharge should be acknowledged without first-recharge handling, ok=%v event=%+v", ok, event)
	}
}

func TestFirstRechargeEventFromWalletMessageKeepsGoogleRecharge(t *testing.T) {
	// Google 充值仍按商品 ID 进入首充奖励链路，缺商品字段应由 wallet outbox 事实修正，而不是泛化吞掉。
	body, err := walletmq.EncodeWalletOutboxMessage(walletmq.WalletOutboxMessage{
		AppCode:        "lalu",
		EventID:        "wev-google",
		EventType:      firstrechargedomain.RechargeEventWalletRecorded,
		TransactionID:  "wtx-google",
		CommandID:      "google-pay-1",
		UserID:         42001,
		AssetType:      "COIN",
		AvailableDelta: 160000,
		PayloadJSON:    `{"recharge_type":"google","google_product_id":"coins_160000","recharge_usd_minor":199,"recharge_sequence":1}`,
		OccurredAtMS:   1710000000000,
	})
	if err != nil {
		t.Fatalf("EncodeWalletOutboxMessage failed: %v", err)
	}

	event, ok, err := firstRechargeEventFromWalletMessage(body)
	if err != nil {
		t.Fatalf("firstRechargeEventFromWalletMessage returned error: %v", err)
	}
	if !ok || event.RechargeType != "google" || event.GoogleProductID != "coins_160000" {
		t.Fatalf("google recharge should be routed to first-recharge handling, ok=%v event=%+v", ok, event)
	}
}
