package integration

import (
	"testing"

	"google.golang.org/protobuf/proto"
	luckygifteventsv1 "hyapp.local/api/proto/events/luckygift/v1"
	"hyapp/pkg/luckygiftmq"
)

func TestLuckyGiftRocketMessageUsesOwnerEventIdentity(t *testing.T) {
	fact, err := proto.Marshal(&luckygifteventsv1.LuckyGiftDrawn{
		DrawId:               "draw-10x",
		CommandId:            "cmd-10x",
		RoomId:               "room-1",
		GiftId:               "43",
		GiftCount:            1,
		SenderUserId:         123456,
		TargetUserId:         654321,
		CoinSpent:            100,
		MultiplierPpm:        luckygiftmq.LuckyGiftDisplayMinMultiplierPPM,
		EffectiveRewardCoins: 1000,
		RewardStatus:         "granted",
		DrawCreatedAtMs:      1783940398274,
		RewardGrantedAtMs:    1783940398374,
	})
	if err != nil {
		t.Fatalf("marshal lucky fact: %v", err)
	}
	envelope := &luckygifteventsv1.EventEnvelope{
		EventId:      "lucky_gift_drawn:draw-10x",
		EventType:    luckygiftmq.EventTypeLuckyGiftDrawn,
		AppCode:      "lalu",
		DrawId:       "draw-10x",
		OccurredAtMs: 1783940398274,
		Body:         fact,
	}

	message, err := luckyGiftRocketMessage("hyapp_lucky_gift_outbox", envelope)
	if err != nil {
		t.Fatalf("build RocketMQ message: %v", err)
	}
	if message.Topic != "hyapp_lucky_gift_outbox" || message.Tag != luckygiftmq.EventTypeLuckyGiftDrawn {
		t.Fatalf("unexpected routing: topic=%q tag=%q", message.Topic, message.Tag)
	}
	if len(message.Keys) != 2 || message.Keys[0] != envelope.GetEventId() || message.Keys[1] != envelope.GetDrawId() {
		t.Fatalf("unexpected keys: %v", message.Keys)
	}
	decoded, _, err := luckygiftmq.DecodeLuckyGiftOutboxMessage(message.Body)
	if err != nil {
		t.Fatalf("decode RocketMQ body: %v", err)
	}
	if decoded.GetEventId() != envelope.GetEventId() || decoded.GetOccurredAtMs() != envelope.GetOccurredAtMs() {
		t.Fatalf("decoded envelope mismatch: %+v", decoded)
	}
}
