package postgres

import (
	"testing"
	"time"

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

// TestPackageUsageRejectsNewEmptyTermsSnapshot 验证迁移约束拒绝上线后新增空计时快照。
func TestPackageUsageRejectsNewEmptyTermsSnapshot(t *testing.T) {
	tx := testutil.NewPostgresTransaction(t)
	usage := newTermsSnapshotTestUsage()
	if err := tx.Create(usage).Error; err == nil {
		t.Fatal("新增套餐使用记录缺少计时快照时必须被数据库拒绝")
	}
}

// TestPackageUsageAcceptsCompleteTermsSnapshot 验证完整计时快照可与使用记录一次性落库。
func TestPackageUsageAcceptsCompleteTermsSnapshot(t *testing.T) {
	tx := testutil.NewPostgresTransaction(t)
	usage := newTermsSnapshotTestUsage()
	usage.ExpiryBaseSnapshot = constants.PackageExpiryBaseFromPurchase
	usage.CalendarTypeSnapshot = constants.PackageCalendarTypeByDay
	usage.DurationDaysSnapshot = 30
	if err := tx.Create(usage).Error; err != nil {
		t.Fatalf("完整计时快照应可落库：%v", err)
	}
}

// TestHistoricalPackageUsageWithoutTermsSnapshotCanUpdateStatus 验证历史空快照可继续状态流转。
func TestHistoricalPackageUsageWithoutTermsSnapshotCanUpdateStatus(t *testing.T) {
	tx := testutil.NewPostgresTransaction(t)
	if err := tx.Exec("ALTER TABLE tb_package_usage DISABLE TRIGGER trg_validate_package_usage_terms_snapshot").Error; err != nil {
		t.Fatalf("禁用快照校验触发器失败：%v", err)
	}
	usage := newTermsSnapshotTestUsage()
	if err := tx.Create(usage).Error; err != nil {
		t.Fatalf("构造历史空快照记录失败：%v", err)
	}
	if err := tx.Exec("ALTER TABLE tb_package_usage ENABLE TRIGGER trg_validate_package_usage_terms_snapshot").Error; err != nil {
		t.Fatalf("恢复快照校验触发器失败：%v", err)
	}
	if err := tx.Model(&usage).Update("status", usage.Status).Error; err != nil {
		t.Fatalf("历史空快照记录应可继续更新状态：%v", err)
	}
}

func newTermsSnapshotTestUsage() *model.PackageUsage {
	unique := uint(time.Now().UnixNano() & 0x7fffffff)
	return &model.PackageUsage{
		OrderID: unique, OrderNo: "UR55-SNAPSHOT-TEST", PackageID: unique,
		UsageType: constants.AssetWalletResourceTypeIotCard, IotCardID: unique,
		DataLimitMB: 1, Status: constants.PackageUsageStatusPending,
		Priority: 1, PackageName: "UR55测试套餐", Generation: 1,
	}
}
