package mysql

import (
	"testing"
	"time"

	"hyapp/services/wallet-service/internal/domain/ledger"
)

func TestVipActivationWindowReplaceFromNowDropsUpgradeRemainder(t *testing.T) {
	nowMS := time.Now().UnixMilli()
	durationMS := int64(30 * 24 * time.Hour / time.Millisecond)
	current := ledger.UserVip{
		Level:       3,
		Active:      true,
		StartedAtMS: nowMS - durationMS,
		ExpiresAtMS: nowMS + int64(15*24*time.Hour/time.Millisecond),
	}
	startedAtMS, expiresAtMS, err := vipActivationWindow(current, ledger.VipLevel{Level: 4, DurationMS: durationMS}, ledger.VipExpiryPolicyReplaceFromNow, nowMS)
	if err != nil {
		t.Fatalf("vipActivationWindow failed: %v", err)
	}
	if startedAtMS != nowMS || expiresAtMS != nowMS+durationMS {
		t.Fatalf("higher Fami VIP must replace from now: started=%d expires=%d now=%d duration=%d", startedAtMS, expiresAtMS, nowMS, durationMS)
	}
}

func TestVipActivationWindowKeepsSameLevelRenewalAndLegacyUpgrade(t *testing.T) {
	nowMS := time.Now().UnixMilli()
	durationMS := int64(7 * 24 * time.Hour / time.Millisecond)
	current := ledger.UserVip{Level: 3, Active: true, StartedAtMS: nowMS - durationMS, ExpiresAtMS: nowMS + durationMS}
	for _, testCase := range []struct {
		name   string
		level  int32
		policy string
	}{
		{name: "same level in P1", level: 3, policy: ledger.VipExpiryPolicyReplaceFromNow},
		{name: "legacy upgrade", level: 4, policy: ledger.VipExpiryPolicyExtendRemaining},
	} {
		t.Run(testCase.name, func(t *testing.T) {
			startedAtMS, expiresAtMS, err := vipActivationWindow(current, ledger.VipLevel{Level: testCase.level, DurationMS: durationMS}, testCase.policy, nowMS)
			if err != nil {
				t.Fatalf("vipActivationWindow failed: %v", err)
			}
			if startedAtMS != current.StartedAtMS || expiresAtMS != current.ExpiresAtMS+durationMS {
				t.Fatalf("renew/legacy must extend remaining time: started=%d expires=%d", startedAtMS, expiresAtMS)
			}
		})
	}
}
