package user

import (
	"testing"
	"time"

	modeluser "github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/types"
)

func TestBuildUserSubscribeListItem(t *testing.T) {
	trafficLimitJSON := `[{"stat_type":"day","stat_value":1,"traffic_usage":10,"speed_limit":5}]`
	now := time.Unix(1718000000, 0)

	tests := []struct {
		name             string
		item             *modeluser.SubscribeDetails
		wantTrafficLimit []types.TrafficLimit
	}{
		{
			name: "non-empty user traffic limit",
			item: &modeluser.SubscribeDetails{
				Id:           1,
				UserId:       2,
				NodeGroupId:  3,
				Token:        "token-12345678",
				TrafficLimit: &trafficLimitJSON,
				StartTime:    now,
				ExpireTime:   now,
			},
			wantTrafficLimit: []types.TrafficLimit{
				{
					StatType:     "day",
					StatValue:    1,
					TrafficUsage: 10,
					SpeedLimit:   5,
				},
			},
		},
		{
			name: "empty user traffic limit",
			item: &modeluser.SubscribeDetails{
				Id:          4,
				UserId:      5,
				NodeGroupId: 6,
				Token:       "token-empty",
				StartTime:   now,
				ExpireTime:  now,
			},
			wantTrafficLimit: nil,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got := buildUserSubscribeListItem(tc.item, "group-a")
			if got.NodeGroupName != "group-a" {
				t.Fatalf("NodeGroupName = %q, want %q", got.NodeGroupName, "group-a")
			}
			if len(got.Short) != 8 {
				t.Fatalf("Short length = %d, want 8", len(got.Short))
			}
			if len(got.TrafficLimit) != len(tc.wantTrafficLimit) {
				t.Fatalf("TrafficLimit length = %d, want %d", len(got.TrafficLimit), len(tc.wantTrafficLimit))
			}
			for i := range tc.wantTrafficLimit {
				if got.TrafficLimit[i] != tc.wantTrafficLimit[i] {
					t.Fatalf("TrafficLimit[%d] = %+v, want %+v", i, got.TrafficLimit[i], tc.wantTrafficLimit[i])
				}
			}
		})
	}
}
