package packagedomain

import (
	"testing"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

// TestResolveTermsSnapshot 验证默认、覆盖及两种周期规则。
func TestResolveTermsSnapshot(t *testing.T) {
	overridePurchase := constants.PackageExpiryBaseFromPurchase
	overrideActivation := constants.PackageExpiryBaseFromActivation
	tests := []struct {
		name            string
		pkg             model.Package
		allocation      *model.ShopPackageAllocation
		wantErr         bool
		wantExpiryBase  string
	}{
		{name: "自然月默认", pkg: model.Package{ExpiryBase: constants.PackageExpiryBaseFromActivation, CalendarType: constants.PackageCalendarTypeNaturalMonth, DurationMonths: 12}, wantExpiryBase: constants.PackageExpiryBaseFromActivation},
		{name: "from_purchase 覆盖", pkg: model.Package{ExpiryBase: constants.PackageExpiryBaseFromActivation, CalendarType: constants.PackageCalendarTypeByDay, DurationDays: 30}, allocation: &model.ShopPackageAllocation{ExpiryBaseOverride: &overridePurchase}, wantExpiryBase: constants.PackageExpiryBaseFromPurchase},
		{name: "from_activation 覆盖", pkg: model.Package{ExpiryBase: constants.PackageExpiryBaseFromPurchase, CalendarType: constants.PackageCalendarTypeByDay, DurationDays: 14}, allocation: &model.ShopPackageAllocation{ExpiryBaseOverride: &overrideActivation}, wantExpiryBase: constants.PackageExpiryBaseFromActivation},
		{name: "非法生效条件", pkg: model.Package{ExpiryBase: "invalid", CalendarType: constants.PackageCalendarTypeByDay, DurationDays: 30}, wantErr: true},
		{name: "非法按天时长", pkg: model.Package{ExpiryBase: constants.PackageExpiryBaseFromPurchase, CalendarType: constants.PackageCalendarTypeByDay}, wantErr: true},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			got, err := ResolveTermsSnapshot(&test.pkg, test.allocation)
			if (err != nil) != test.wantErr {
				t.Fatalf("错误状态不符合预期：%v", err)
			}
			if !test.wantErr && !got.IsValid() {
				t.Fatalf("快照应有效：%+v", got)
			}
			if !test.wantErr && test.wantExpiryBase != "" && got.ExpiryBase != test.wantExpiryBase {
				t.Fatalf("生效条件不符预期：want=%s got=%s", test.wantExpiryBase, got.ExpiryBase)
			}
		})
	}
}
