package listing

import "testing"

func TestFilterPublicListingsByRatio(t *testing.T) {
	minRatio := 20.0
	maxRatio := 30.0
	items := []ListingDTO{
		{ID: 1, HafCoinAmount: 100_000_000, PriceCent: 10_000, AssetSummary: map[string]any{"publish_ratio": 10.0}},
		{ID: 2, HafCoinAmount: 100_000_000, PriceCent: 4_000, AssetSummary: map[string]any{"publish_ratio": 25.0}},
		{ID: 3, HafCoinAmount: 100_000_000, PriceCent: 2_500, AssetSummary: map[string]any{"publish_ratio": 40.0}},
	}

	filtered := filterPublicListings(items, PublicListQuery{
		MinRatio: &minRatio,
		MaxRatio: &maxRatio,
	})

	if len(filtered) != 1 || filtered[0].ID != 2 {
		t.Fatalf("expected only listing 2 in ratio range, got %#v", filtered)
	}
}

func TestSortPublicListingsDefaultUsesShuffleKey(t *testing.T) {
	items := []ListingDTO{
		{ID: 101},
		{ID: 102},
		{ID: 103},
		{ID: 104},
	}

	sortPublicListings(items, "recommended")

	for index := 1; index < len(items); index++ {
		previous := publicShuffleKey(items[index-1].ID)
		current := publicShuffleKey(items[index].ID)
		if previous > current {
			t.Fatalf("expected shuffled order by key, got ids=%v", []uint64{
				items[0].ID,
				items[1].ID,
				items[2].ID,
				items[3].ID,
			})
		}
	}
}

func TestIsNightAvailableSummaryUsesMidnightToEight(t *testing.T) {
	tests := []struct {
		name  string
		start string
		end   string
		want  bool
	}{
		{name: "全天可上号", start: "00:00", end: "23:59", want: true},
		{name: "覆盖夜间新区间", start: "00:00", end: "08:00", want: true},
		{name: "刚好八点开始", start: "08:00", end: "12:00", want: true},
		{name: "八点半开始不算夜间", start: "08:30", end: "12:00", want: false},
		{name: "跨零点覆盖夜间", start: "23:00", end: "02:00", want: true},
		{name: "旧夜间晚间时段不再命中", start: "22:00", end: "23:00", want: false},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := isNightAvailableSummary(map[string]any{
				"online_time": map[string]any{
					"start": tt.start,
					"end":   tt.end,
				},
			})
			if got != tt.want {
				t.Fatalf("isNightAvailableSummary(%s-%s) = %v, want %v", tt.start, tt.end, got, tt.want)
			}
		})
	}
}
