package levelconfig

import (
	"testing"

	activityv1 "hyapp.local/api/proto/activity/v1"
)

func TestMergeRuleDisplayResourcesPreservesDisplayConfig(t *testing.T) {
	badgeID := int64(9001)
	avatarFrameID := int64(9101)
	shortBadgeID := int64(9201)
	raw, err := mergeRuleDisplayResources(`{"theme":"gold"}`, &badgeID, &avatarFrameID, &shortBadgeID)
	if err != nil {
		t.Fatalf("mergeRuleDisplayResources failed: %v", err)
	}
	if got := longBadgeResourceID(raw); got != badgeID {
		t.Fatalf("long badge id mismatch: got=%d raw=%s", got, raw)
	}
	if got := avatarFrameResourceID(raw); got != avatarFrameID {
		t.Fatalf("avatar frame id mismatch: got=%d raw=%s", got, raw)
	}
	if got := shortBadgeResourceID(raw); got != shortBadgeID {
		t.Fatalf("short badge id mismatch: got=%d raw=%s", got, raw)
	}
	config, err := objectFromJSON(raw)
	if err != nil {
		t.Fatalf("objectFromJSON failed: %v", err)
	}
	if config["theme"] != "gold" {
		t.Fatalf("display config field lost: %+v", config)
	}
}

func TestConfigFromProtoGroupsRulesAndTiers(t *testing.T) {
	resp := &activityv1.ListLevelConfigResponse{
		Tracks: []*activityv1.LevelTrack{{Track: "wealth", Name: "财富等级", Status: "active"}},
		Rules: []*activityv1.LevelRule{{
			Track:             "wealth",
			Level:             3,
			RequiredValue:     300,
			DisplayConfigJson: `{"long_badge_resource_id":7003,"avatar_frame_resource_id":8103,"short_badge_resource_id":7103}`,
		}},
		Tiers: []*activityv1.LevelTier{{
			TierId:                 11,
			Track:                  "wealth",
			MinLevel:               1,
			MaxLevel:               10,
			DisplayBadgeResourceId: 9001,
		}},
		ServerTimeMs: 123,
	}
	dto := configFromProto(resp)
	if len(dto.Tracks) != 1 || dto.Tracks[0].Track != "wealth" {
		t.Fatalf("track grouping mismatch: %+v", dto.Tracks)
	}
	if len(dto.Tracks[0].Rules) != 1 || dto.Tracks[0].Rules[0].LongBadgeResourceID != 7003 {
		t.Fatalf("rule long badge mismatch: %+v", dto.Tracks[0].Rules)
	}
	if dto.Tracks[0].Rules[0].AvatarFrameResourceID != 8103 {
		t.Fatalf("rule avatar frame mismatch: %+v", dto.Tracks[0].Rules)
	}
	if dto.Tracks[0].Rules[0].ShortBadgeResourceID != 7103 {
		t.Fatalf("rule short badge mismatch: %+v", dto.Tracks[0].Rules)
	}
	if len(dto.Tracks[0].Tiers) != 1 || dto.Tracks[0].Tiers[0].DisplayBadgeResourceID != 9001 {
		t.Fatalf("tier grouping mismatch: %+v", dto.Tracks[0].Tiers)
	}
}
