package service_test

import (
	"context"
	"testing"
	"time"

	roomv1 "hyapp.local/api/proto/room/v1"
	walletv1 "hyapp.local/api/proto/wallet/v1"
	"hyapp/pkg/appcode"
	"hyapp/services/room-service/internal/integration"
	roomservice "hyapp/services/room-service/internal/room/service"
	"hyapp/services/room-service/internal/router"
	"hyapp/services/room-service/internal/testutil/mysqltest"
)

type recordingRoomGiftLeaderboard struct {
	increments []roomservice.RoomGiftLeaderboardIncrement
}

func (s *recordingRoomGiftLeaderboard) IncrementRoomGift(_ context.Context, input roomservice.RoomGiftLeaderboardIncrement) error {
	s.increments = append(s.increments, input)
	return nil
}

func (s *recordingRoomGiftLeaderboard) ListRoomGiftLeaderboard(context.Context, roomservice.RoomGiftLeaderboardQuery) (roomservice.RoomGiftLeaderboardPage, error) {
	return roomservice.RoomGiftLeaderboardPage{}, nil
}

func TestSendGiftWritesRoomGiftLeaderboardWithHeatValue(t *testing.T) {
	ctx := context.Background()
	repository := mysqltest.NewRepository(t)
	wallet := &rocketTestWallet{debits: []*walletv1.DebitGiftResponse{{
		BillingReceiptId: "receipt-gift-leaderboard",
		CoinSpent:        100,
		ChargeAmount:     100,
		GiftPointAdded:   100,
		HeatValue:        10,
		GiftTypeCode:     "lucky",
	}}}
	leaderboard := &recordingRoomGiftLeaderboard{}
	now := &fixedRoomRocketClock{now: time.Date(2026, 6, 5, 12, 0, 0, 0, time.UTC)}
	svc := roomservice.New(roomservice.Config{
		NodeID:              "node-gift-leaderboard-test",
		LeaseTTL:            10 * time.Second,
		RankLimit:           20,
		SnapshotEveryN:      1,
		Clock:               now,
		RoomGiftLeaderboard: leaderboard,
	}, router.NewMemoryDirectory(), repository, wallet, integration.NewNoopRoomEventPublisher(), integration.NewNoopOutboxPublisher())

	roomID := "room-gift-leaderboard"
	senderID := int64(18001)
	targetID := int64(18002)
	createRocketRoom(t, ctx, svc, roomID, senderID, 9001)
	joinRocketRoom(t, ctx, svc, roomID, targetID)

	if _, err := svc.SendGift(ctx, &roomv1.SendGiftRequest{
		Meta: &roomv1.RequestMeta{
			RequestId:   "req-gift-leaderboard",
			CommandId:   "cmd-gift-leaderboard",
			ActorUserId: senderID,
			RoomId:      roomID,
			AppCode:     appcode.Default,
			SentAtMs:    now.Now().UnixMilli(),
		},
		TargetType:   "user",
		TargetUserId: targetID,
		GiftId:       "gift-leaderboard",
		GiftCount:    1,
	}); err != nil {
		t.Fatalf("send gift failed: %v", err)
	}

	if len(leaderboard.increments) != 1 {
		t.Fatalf("expected one leaderboard increment, got %+v", leaderboard.increments)
	}
	if leaderboard.increments[0].CoinSpent != 10 {
		t.Fatalf("leaderboard must use heat value after global ratio, got %+v", leaderboard.increments[0])
	}
}
