package packagepkg

import (
	"testing"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"go.uber.org/zap"
)

// TestResolveUsageTerms 验证快照优先、历史完整空值回退和部分缺失拒绝。
func TestResolveUsageTerms(t *testing.T) {
	pkg := &model.Package{
		ExpiryBase:   constants.PackageExpiryBaseFromActivation,
		CalendarType: constants.PackageCalendarTypeByDay, DurationDays: 30,
	}
	usage := &model.PackageUsage{
		ExpiryBaseSnapshot:     constants.PackageExpiryBaseFromPurchase,
		CalendarTypeSnapshot:   constants.PackageCalendarTypeNaturalMonth,
		DurationMonthsSnapshot: 12,
	}
	terms, err := ResolveUsageTerms(usage, pkg, zap.NewNop())
	if err != nil || terms.ExpiryBase != constants.PackageExpiryBaseFromPurchase || terms.DurationMonths != 12 {
		t.Fatalf("应优先读取不可变快照：%+v, %v", terms, err)
	}

	before := HistoricalTermsFallbackCount()
	historical := &model.PackageUsage{Model: usage.Model}
	terms, err = ResolveUsageTerms(historical, pkg, zap.NewNop())
	if err != nil || terms.DurationDays != 30 || HistoricalTermsFallbackCount() != before+1 {
		t.Fatalf("历史空快照应可观测回退：%+v, %v", terms, err)
	}

	broken := &model.PackageUsage{ExpiryBaseSnapshot: constants.PackageExpiryBaseFromPurchase}
	if _, err = ResolveUsageTerms(broken, pkg, zap.NewNop()); err == nil {
		t.Fatal("部分缺失快照必须拒绝")
	}
}

// TestResolveUsageTermsKeepsPurchasedTerms 验证购买后修改套餐配置不改变已有使用记录语义。
func TestResolveUsageTermsKeepsPurchasedTerms(t *testing.T) {
	usage := &model.PackageUsage{
		ExpiryBaseSnapshot:   constants.PackageExpiryBaseFromPurchase,
		CalendarTypeSnapshot: constants.PackageCalendarTypeByDay,
		DurationDaysSnapshot: 90,
	}
	pkg := &model.Package{
		ExpiryBase:     constants.PackageExpiryBaseFromActivation,
		CalendarType:   constants.PackageCalendarTypeNaturalMonth,
		DurationMonths: 1,
	}
	terms, err := ResolveUsageTerms(usage, pkg, zap.NewNop())
	if err != nil {
		t.Fatalf("读取购买快照失败：%v", err)
	}
	if terms.ExpiryBase != constants.PackageExpiryBaseFromPurchase || terms.CalendarType != constants.PackageCalendarTypeByDay || terms.DurationDays != 90 {
		t.Fatalf("套餐当前配置不应覆盖购买快照：%+v", terms)
	}
}
