package ledger

import "strings"

const (
	// AssetCoin 是用户送礼消费资产。
	AssetCoin = "COIN"
	// AssetCoinSellerCoin 是币商专用金币资产，只能通过币商转账兑换成玩家普通 COIN。
	AssetCoinSellerCoin = "COIN_SELLER_COIN"
	// AssetGiftPoint 是历史礼物积分资产，只保留历史账本查询兼容；新送礼不会再给它入账。
	AssetGiftPoint = "GIFT_POINT"
	// AssetHostPeriodDiamond 是主播工资周期钻石投影，只参与工资等级结算，不进入通用钱包余额。
	AssetHostPeriodDiamond = "HOST_PERIOD_DIAMOND"
	// AssetHostSalaryUSD 是主播工资美元钱包，只接收主播工资和月底剩余钻石折美元。
	AssetHostSalaryUSD = "HOST_SALARY_USD"
	// AssetAgencySalaryUSD 是代理工资美元钱包，只接收主播结算同时产生的代理工资。
	AssetAgencySalaryUSD = "AGENCY_SALARY_USD"
	// AssetBDSalaryUSD 是 BD 工资美元钱包，只接收 BD 政策结算工资。
	AssetBDSalaryUSD = "BD_SALARY_USD"
	// AssetAdminSalaryUSD 是 Admin 工资美元钱包，只接收 Admin 政策结算工资。
	AssetAdminSalaryUSD = "ADMIN_SALARY_USD"
	// SalaryExchangeCoinPerUSD 是工资直接兑换普通金币的固定比例，金额以 1 USD 为单位。
	SalaryExchangeCoinPerUSD int64 = 80000

	// StockTypeUSDTPurchase 表示币商线下 USDT 进货后发放专用金币库存。
	StockTypeUSDTPurchase = "usdt_purchase"
	// StockTypeCoinCompensation 表示平台人工补偿币商专用金币库存，不计入进货金额。
	StockTypeCoinCompensation = "coin_compensation"
	// PaidCurrencyUSDT 是首版币商进货支持的唯一线下付款币种。
	PaidCurrencyUSDT = "USDT"
	// RechargeProductStatusActive 表示内购商品已上架，可进入 App 充值页。
	RechargeProductStatusActive = "active"
	// RechargeProductStatusDisabled 表示内购商品未上架，仅后台可见。
	RechargeProductStatusDisabled = "disabled"
	// RechargeProductPlatformAndroid 表示 Google Play 侧内购商品。
	RechargeProductPlatformAndroid = "android"
	// RechargeProductPlatformIOS 表示 Apple IAP 侧内购商品。
	RechargeProductPlatformIOS = "ios"
	// RechargeProductPlatformWeb 表示 H5 站外充值商品，支付方式由订单选择，不绑定应用商店。
	RechargeProductPlatformWeb = "web"
	// RechargeAudienceNormal 表示普通用户可购买的充值档位。
	RechargeAudienceNormal = "normal"
	// RechargeAudienceCoinSeller 表示币商可购买的充值档位。
	RechargeAudienceCoinSeller = "coin_seller"
	// RechargeChannelGoogle 是 android 平台内购渠道标识。
	RechargeChannelGoogle = "google"
	// RechargeChannelApple 是 iOS 平台内购渠道标识。
	RechargeChannelApple = "apple"
	// RechargeChannelExternal 是 H5 站外充值渠道，具体 provider 在外部订单上保存。
	RechargeChannelExternal = "external"
	// PaymentProviderGooglePlay 是 Google Play 一次性内购支付渠道。
	PaymentProviderGooglePlay = "google_play"
	// PaymentProviderMifaPay 是 MiFaPay 三方收银台支付渠道。
	PaymentProviderMifaPay = "mifapay"
	// PaymentProviderUSDTTRC20 是用户提交 TRC20 链上交易哈希的 USDT 充值渠道。
	PaymentProviderUSDTTRC20 = "usdt_trc20"
	// ThirdPartyPaymentStatusActive 表示渠道或支付方式可用于 H5 下单。
	ThirdPartyPaymentStatusActive = "active"
	// ThirdPartyPaymentStatusDisabled 表示渠道或支付方式已被后台关闭。
	ThirdPartyPaymentStatusDisabled = "disabled"
	// ExternalRechargeStatusPending 表示外部充值订单已创建但尚未确认到账。
	ExternalRechargeStatusPending = "pending"
	// ExternalRechargeStatusRedirected 表示 MiFaPay 下单成功，用户已拿到跳转链接。
	ExternalRechargeStatusRedirected = "redirected"
	// ExternalRechargeStatusCredited 表示外部充值已完成钱包入账。
	ExternalRechargeStatusCredited = "credited"
	// ExternalRechargeStatusFailed 表示外部充值被验签、金额或链上校验拒绝。
	ExternalRechargeStatusFailed = "failed"
	// PaymentStatusCredited 表示支付已完成校验并入账。
	PaymentStatusCredited = "credited"
	// PaymentConsumeStatePending 表示已入账但 Google consume 尚未确认完成。
	PaymentConsumeStatePending = "consume_pending"
	// PaymentConsumeStateConsumed 表示 Google consume 已确认完成。
	PaymentConsumeStateConsumed = "consumed"
	// GooglePurchaseStatePurchased 是 Google Play 已支付完成状态。
	GooglePurchaseStatePurchased = "PURCHASED"

	// HostSalarySettlementModeDaily 表示主播工资按日结算等级增量。
	HostSalarySettlementModeDaily = "daily"
	// HostSalarySettlementModeHalfMonth 表示主播工资按半月周期结算等级增量。
	HostSalarySettlementModeHalfMonth = "half_month"
	// HostSalarySettlementTypeMonthEnd 表示月底清算等级增量、剩余钻石折美元和周期关闭。
	HostSalarySettlementTypeMonthEnd = "month_end"
	// HostSalarySettlementTriggerAutomatic 表示由 cron-service 自动扫描结算的政策。
	HostSalarySettlementTriggerAutomatic = "automatic"
	// HostSalarySettlementTriggerManual 表示只允许后台工资结算页人工触发的政策。
	HostSalarySettlementTriggerManual = "manual"

	// VipStatusActive 表示 VIP 配置或用户会员状态当前有效。
	VipStatusActive = "active"
	// VipStatusDisabled 表示 VIP 配置被后台停用。
	VipStatusDisabled = "disabled"
	// VipGrantSourcePurchase 表示用户主动购买或续费 VIP。
	VipGrantSourcePurchase = "vip_purchase"
	// VipGrantSourceActivity 表示活动系统赠送 VIP。
	VipGrantSourceActivity = "activity_grant"
	// VipGrantSourceAdmin 表示后台人工赠送 VIP。
	VipGrantSourceAdmin = "admin_grant"
	// VipGrantSourceManagerCenter 表示经理中心按权限赠送 VIP，账务仍复用后台赠送激活链路。
	VipGrantSourceManagerCenter = "manager_center"

	// GameOpDebit 表示游戏平台下注、局内道具等扣金币行为。
	GameOpDebit = "debit"
	// GameOpCredit 表示游戏平台中奖、派奖等加金币行为。
	GameOpCredit = "credit"
	// GameOpRefund 表示游戏平台扣款失败或取消后的退款入账。
	GameOpRefund = "refund"
	// GameOpReverse 表示平台冲正；首版按扣回用户 COIN 处理。
	GameOpReverse = "reverse"

	// RedPacketTypeNormal 表示发出后立即可抢的普通红包。
	RedPacketTypeNormal = "normal"
	// RedPacketTypeDelayed 表示发出后按后台秒数延迟打开的红包。
	RedPacketTypeDelayed = "delayed"
	// RedPacketStatusWaitingOpen 表示延迟红包已扣款但未到打开时间。
	RedPacketStatusWaitingOpen = "waiting_open"
	// RedPacketStatusActive 表示红包可领取。
	RedPacketStatusActive = "active"
	// RedPacketStatusFinished 表示红包所有份额已领取。
	RedPacketStatusFinished = "finished"
	// RedPacketStatusRefunded 表示红包过期未领取金额已退回。
	RedPacketStatusRefunded = "refunded"
	// RedPacketClaimStatusClaimed 表示红包份额领取成功。
	RedPacketClaimStatusClaimed = "claimed"

	// RedPacketExpireSeconds 固定房内红包 24 小时过期退款。
	RedPacketExpireSeconds int32 = 24 * 60 * 60
)

// DebitGiftCommand 是 room-service 送礼扣费的账务命令。
type DebitGiftCommand struct {
	AppCode      string
	CommandID    string
	RoomID       string
	SenderUserID int64
	TargetUserID int64
	GiftID       string
	GiftCount    int32
	PriceVersion string
	RegionID     int64
	// SenderRegionID 是送礼用户所属区域；用于按区域匹配礼物入主播周期钻石比例。
	SenderRegionID int64
	// TargetIsHost 只能由 gateway 根据 user-service active host profile 注入，客户端输入不可信。
	TargetIsHost bool
	// TargetHostRegionID 是主播身份所属区域；工资政策按该区域匹配，不能用房间可见区域替代。
	TargetHostRegionID int64
	// TargetAgencyOwnerUserID 是送礼瞬间主播上级代理的收款用户快照；结算按快照发放，避免月底组织变化错账。
	TargetAgencyOwnerUserID int64
}

// DebitGiftTargetCommand 是批量送礼中单个接收方的账务语义。
type DebitGiftTargetCommand struct {
	// CommandID 是单个目标交易的幂等键；同一批量送礼必须为每个目标派生独立值。
	CommandID string
	// TargetUserID 是本次收礼用户；GIFT_POINT 已下线，新送礼不会再给目标用户积分入账。
	TargetUserID int64
	// TargetIsHost 只能由 gateway 注入，批量目标之间不能共享该身份快照。
	TargetIsHost bool
	// TargetHostRegionID 是该目标主播身份所属区域。
	TargetHostRegionID int64
	// TargetAgencyOwnerUserID 是该目标主播当前代理 owner 收款快照。
	TargetAgencyOwnerUserID int64
}

// BatchDebitGiftCommand 在一个钱包事务中结算同一 sender 对多个 target 的同款礼物。
type BatchDebitGiftCommand struct {
	AppCode        string
	CommandID      string
	RoomID         string
	SenderUserID   int64
	GiftID         string
	GiftCount      int32
	PriceVersion   string
	RegionID       int64
	SenderRegionID int64
	Targets        []DebitGiftTargetCommand
}

// Receipt 是账务命令落账后的稳定回执。
type Receipt struct {
	BillingReceiptID string
	TransactionID    string
	CoinSpent        int64
	ChargeAssetType  string
	ChargeAmount     int64
	// GiftPointAdded 是历史回执字段，新送礼固定为 0；房间贡献和主播周期钻石只按真实扣费金额计算。
	GiftPointAdded int64
	HeatValue      int64
	GiftTypeCode   string
	// CPRelationType 只在 CP 礼物类型上有值，room-service 会把它写入 RoomGiftSent 供 user-service 建关系申请。
	CPRelationType string
	// 礼物展示字段是扣费时的资源快照，避免异步消费者再查礼物配置导致历史 IM 展示被后续配置修改影响。
	GiftName         string
	GiftIconURL      string
	GiftAnimationURL string
	GiftEffectTypes  []string
	PriceVersion     string
	BalanceAfter     int64
	// HostPeriodDiamondAdded 是本次送礼写入主播工资周期账户的钻石数；非主播恒为 0。
	HostPeriodDiamondAdded int64
	// HostPeriodCycleKey 是工资周期键，当前按 UTC 月生成，后续结算按此键定位周期账户。
	HostPeriodCycleKey string
}

// BatchGiftTargetReceipt 保留批量送礼里每个目标的独立交易回执。
type BatchGiftTargetReceipt struct {
	TargetUserID int64
	CommandID    string
	Receipt      Receipt
}

// BatchGiftReceipt 同时返回聚合展示值和逐目标事实回执。
type BatchGiftReceipt struct {
	Aggregate Receipt
	Targets   []BatchGiftTargetReceipt
}

// HostSalarySettlementBatchCommand 是 cron 或测试触发结算批处理的最小输入。
type HostSalarySettlementBatchCommand struct {
	AppCode        string
	RunID          string
	WorkerID       string
	BatchSize      int
	SettlementType string
	// TriggerMode 决定本次批处理读取自动政策还是手动政策；空值按 automatic 处理，兼容已有定时任务。
	TriggerMode string
	CycleKey    string
	NowMs       int64
}

// HostSalarySettlementBatchResult 汇总一个结算批次的扫描和入账结果。
type HostSalarySettlementBatchResult struct {
	ClaimedCount   int
	ProcessedCount int
	SuccessCount   int
	FailureCount   int
	HasMore        bool
}

// HostSalaryPolicy 是 wallet-service 结算读取的后台政策运行快照。
type HostSalaryPolicy struct {
	PolicyID                 uint64
	Name                     string
	RegionID                 int64
	Status                   string
	SettlementMode           string
	SettlementTriggerMode    string
	GiftCoinToDiamondRatio   string
	ResidualDiamondToUSDRate string
	EffectiveFromMs          int64
	EffectiveToMs            int64
	Levels                   []HostSalaryPolicyLevel
}

// HostSalaryPolicyLevel 使用累计值表达工资和奖励，结算时只发放“当前累计 - 已发累计”的差额。
type HostSalaryPolicyLevel struct {
	LevelNo              int
	RequiredDiamonds     int64
	HostSalaryUSDMinor   int64
	HostCoinReward       int64
	AgencySalaryUSDMinor int64
	Status               string
	SortOrder            int
}

// HostSalaryProgress 是主播当前工资周期的钻石累计投影，用于 H5 按工资政策计算距离下一等级的差值。
type HostSalaryProgress struct {
	HostUserID        int64
	CycleKey          string
	RegionID          int64
	AgencyOwnerUserID int64
	TotalDiamonds     int64
	GiftDiamondTotal  int64
	UpdatedAtMS       int64
}

// CoinSellerTransferCommand 是币商给玩家转普通金币的账务命令。
type CoinSellerTransferCommand struct {
	AppCode         string
	CommandID       string
	SellerUserID    int64
	TargetUserID    int64
	TargetCountryID int64
	SellerRegionID  int64
	TargetRegionID  int64
	Amount          int64
	Reason          string
}

// CoinSellerTransferReceipt 是币商转账完成后的稳定回执。
type CoinSellerTransferReceipt struct {
	TransactionID              string
	SellerBalanceAfter         int64
	TargetBalanceAfter         int64
	Amount                     int64
	RechargeSequence           int64
	RechargeUSDMinor           int64
	RechargeCurrencyCode       string
	RechargePolicyID           int64
	RechargePolicyVersion      string
	RechargePolicyCoinAmount   int64
	RechargePolicyUSDMinorUnit int64
}

// CoinSellerSalaryExchangeRateTier 是工资转给币商时按区域和美元金额匹配的金币兑换比例。
type CoinSellerSalaryExchangeRateTier struct {
	RegionID    int64
	MinUSDMinor int64
	MaxUSDMinor int64
	CoinPerUSD  int64
	Status      string
	SortOrder   int
	UpdatedAtMS int64
}

// SalaryExchangeCommand 是用户把某个身份工资美元钱包兑换为自己普通金币的账务命令。
type SalaryExchangeCommand struct {
	AppCode         string
	CommandID       string
	UserID          int64
	SalaryAssetType string
	SalaryUSDMinor  int64
	Reason          string
}

// SalaryExchangeReceipt 返回工资扣减和普通金币入账后的双边余额。
type SalaryExchangeReceipt struct {
	TransactionID      string
	UserID             int64
	SalaryAssetType    string
	SalaryBalanceAfter int64
	CoinBalanceAfter   int64
	SalaryUSDMinor     int64
	CoinAmount         int64
	CoinPerUSD         int64
	CreatedAtMS        int64
}

// SalaryTransferToCoinSellerCommand 是用户把某个身份工资美元钱包转给同区域币商专用金币库存的账务命令。
type SalaryTransferToCoinSellerCommand struct {
	AppCode         string
	CommandID       string
	SourceUserID    int64
	SellerUserID    int64
	SalaryAssetType string
	SalaryUSDMinor  int64
	RegionID        int64
	Reason          string
}

// SalaryTransferToCoinSellerReceipt 返回工资扣减和币商库存入账后的双边余额与命中的区间。
type SalaryTransferToCoinSellerReceipt struct {
	TransactionID            string
	SourceUserID             int64
	SellerUserID             int64
	SalaryAssetType          string
	SourceSalaryBalanceAfter int64
	SellerBalanceAfter       int64
	SalaryUSDMinor           int64
	CoinAmount               int64
	CoinPerUSD               int64
	RateMinUSDMinor          int64
	RateMaxUSDMinor          int64
	CreatedAtMS              int64
}

// CoinSellerStockCreditCommand 是后台给币商专用金币库存入账的最小账务命令。
type CoinSellerStockCreditCommand struct {
	AppCode          string
	CommandID        string
	SellerUserID     int64
	SellerCountryID  int64
	SellerRegionID   int64
	StockType        string
	CoinAmount       int64
	PaidCurrencyCode string
	PaidAmountMicro  int64
	PaymentRef       string
	EvidenceRef      string
	OperatorUserID   int64
	Reason           string
}

// CoinSellerStockCreditReceipt 是币商库存入账成功后的稳定回执。
type CoinSellerStockCreditReceipt struct {
	TransactionID          string
	SellerUserID           int64
	SellerCountryID        int64
	SellerRegionID         int64
	StockType              string
	CoinAmount             int64
	PaidCurrencyCode       string
	PaidAmountMicro        int64
	CountsAsSellerRecharge bool
	BalanceAfter           int64
	CreatedAtMS            int64
}

// RechargeBill 是充值账单的只读投影；充值事实由 wallet_recharge_records 保存。
type RechargeBill struct {
	AppCode                string
	TransactionID          string
	CommandID              string
	RechargeType           string
	Status                 string
	ExternalRef            string
	UserID                 int64
	SellerUserID           int64
	SellerRegionID         int64
	TargetRegionID         int64
	PolicyID               int64
	PolicyVersion          string
	CurrencyCode           string
	CoinAmount             int64
	USDMinorAmount         int64
	ExchangeCoinAmount     int64
	ExchangeUSDMinorAmount int64
	CreatedAtMS            int64
}

// ListRechargeBillsQuery 是后台查询所有充值渠道账单的筛选条件。
type ListRechargeBillsQuery struct {
	AppCode      string
	UserID       int64
	SellerUserID int64
	RegionID     int64
	RechargeType string
	Status       string
	Keyword      string
	StartAtMS    int64
	EndAtMS      int64
	Page         int32
	PageSize     int32
}

// WalletFeatureFlags 是 App 钱包入口的开关投影；首版由 wallet-service 固定返回，后续可迁移到配置表。
type WalletFeatureFlags struct {
	RechargeEnabled        bool
	DiamondExchangeEnabled bool
}

// WalletOverview 是我的页和钱包首页共同使用的轻量摘要。
type WalletOverview struct {
	Balances     []AssetBalance
	FeatureFlags WalletFeatureFlags
}

// WalletValueSummary 是我的页钱包卡片的最小余额投影。
type WalletValueSummary struct {
	CoinAmount  int64
	UpdatedAtMS int64
}

// GiftWallResource 是礼物墙展示所需的资源快照字段，避免读取接口再依赖资源配置实时状态。
type GiftWallResource struct {
	AppCode           string
	ResourceID        int64
	ResourceCode      string
	ResourceType      string
	Name              string
	Status            string
	Grantable         bool
	GrantStrategy     string
	WalletAssetType   string
	WalletAssetAmount int64
	UsageScopes       []string
	AssetURL          string
	PreviewURL        string
	AnimationURL      string
	MetadataJSON      string
	SortOrder         int32
	CreatedAtMS       int64
	UpdatedAtMS       int64
}

// GiftWallItem 是当前用户收到礼物的按 gift_id 聚合投影。
type GiftWallItem struct {
	GiftID               string
	GiftName             string
	ResourceID           int64
	Resource             GiftWallResource
	ResourceSnapshotJSON string
	GiftTypeCode         string
	PresentationJSON     string
	GiftCount            int64
	TotalValue           int64
	TotalCoinValue       int64
	TotalDiamondValue    int64
	// TotalGiftPoint 是历史礼物墙字段，新送礼不再累加，保留用于旧数据展示兼容。
	TotalGiftPoint    int64
	TotalHeatValue    int64
	ChargeAssetType   string
	LastPriceVersion  string
	FirstReceivedAtMS int64
	LastReceivedAtMS  int64
	SortOrder         int32
}

// UserGiftWall 汇总礼物墙首屏需要的全量统计和按礼物类型聚合列表。
type UserGiftWall struct {
	Items             []GiftWallItem
	GiftKindCount     int64
	GiftTotalCount    int64
	TotalValue        int64
	TotalCoinValue    int64
	TotalDiamondValue int64
	// TotalGiftPoint 是历史礼物墙汇总字段，新送礼不再累加，保留用于旧数据展示兼容。
	TotalGiftPoint int64
	TotalHeatValue int64
}

// RechargeProduct 是用户充值页读取的充值档位。
type RechargeProduct struct {
	AppCode           string
	AudienceType      string
	ProductID         int64
	ProductCode       string
	ProductName       string
	Description       string
	Platform          string
	Channel           string
	CurrencyCode      string
	AmountMicro       int64
	AmountMinor       int64
	CoinAmount        int64
	PolicyVersion     string
	Enabled           bool
	Status            string
	SortOrder         int32
	RegionIDs         []int64
	ResourceAssetType string
	CreatedByUserID   int64
	UpdatedByUserID   int64
	CreatedAtMS       int64
	UpdatedAtMS       int64
}

// ListRechargeProductsQuery 是后台内购商品配置列表的筛选条件。
type ListRechargeProductsQuery struct {
	AppCode      string
	Status       string
	Platform     string
	AudienceType string
	RegionID     int64
	Keyword      string
	Page         int32
	PageSize     int32
}

// RechargeProductCommand 是后台创建或更新内购商品配置的完整事实输入。
type RechargeProductCommand struct {
	AppCode        string
	AudienceType   string
	ProductID      int64
	AmountMicro    int64
	CoinAmount     int64
	ProductName    string
	Description    string
	Platform       string
	RegionIDs      []int64
	Enabled        bool
	OperatorUserID int64
}

// GooglePaymentCommand 是 App 完成 Google Play 支付后提交给后端确认和入账的命令。
type GooglePaymentCommand struct {
	AppCode        string
	CommandID      string
	UserID         int64
	RegionID       int64
	ProductID      int64
	ProductCode    string
	PackageName    string
	PurchaseToken  string
	OrderID        string
	PurchaseTimeMS int64
}

// GooglePlayPurchase 是 Google Play Developer API 返回的一次性商品购买状态快照。
type GooglePlayPurchase struct {
	PackageName            string
	ProductID              string
	OrderID                string
	PurchaseState          string
	ConsumptionState       string
	AcknowledgementState   string
	PurchaseCompletionTime string
	RawJSON                string
}

// GooglePaymentReceipt 是 Google 支付确认接口返回给 App 的稳定入账回执。
type GooglePaymentReceipt struct {
	PaymentOrderID   string
	TransactionID    string
	Status           string
	ProductID        int64
	ProductCode      string
	CoinAmount       int64
	Balance          AssetBalance
	IdempotentReplay bool
	ConsumeState     string
}

// ThirdPartyPaymentMethod 是 MiFaPay 等三方支付方式的后台配置事实。
type ThirdPartyPaymentMethod struct {
	MethodID          int64
	AppCode           string
	ProviderCode      string
	ProviderName      string
	CountryCode       string
	CountryName       string
	CurrencyCode      string
	PayWay            string
	PayType           string
	MethodName        string
	LogoURL           string
	Status            string
	USDToCurrencyRate string
	SortOrder         int32
	CreatedAtMS       int64
	UpdatedAtMS       int64
}

// ThirdPartyPaymentChannel 聚合一个三方渠道及其国家/方式列表，供后台展开展示。
type ThirdPartyPaymentChannel struct {
	AppCode      string
	ProviderCode string
	ProviderName string
	Status       string
	SortOrder    int32
	Methods      []ThirdPartyPaymentMethod
}

type ListThirdPartyPaymentChannelsQuery struct {
	AppCode                string
	ProviderCode           string
	Status                 string
	IncludeDisabledMethods bool
}

type ThirdPartyPaymentMethodStatusCommand struct {
	AppCode        string
	MethodID       int64
	Enabled        bool
	OperatorUserID int64
}

type ThirdPartyPaymentRateCommand struct {
	AppCode           string
	MethodID          int64
	USDToCurrencyRate string
	OperatorUserID    int64
}

// H5RechargeOptionsQuery 是站外充值页在账号确认后读取商品和支付方式的最小条件。
type H5RechargeOptionsQuery struct {
	AppCode           string
	TargetUserID      int64
	TargetRegionID    int64
	TargetCountryCode string
	AudienceType      string
}

type H5RechargeOptions struct {
	Products         []RechargeProduct
	PaymentMethods   []ThirdPartyPaymentMethod
	USDTTRC20Enabled bool
	USDTTRC20Address string
}

// ExternalRechargeOrder 保存 H5 外部充值订单的订单、支付和入账状态。
type ExternalRechargeOrder struct {
	OrderID             string
	AppCode             string
	CommandID           string
	TargetUserID        int64
	TargetRegionID      int64
	TargetCountryCode   string
	AudienceType        string
	ProductID           int64
	ProductCode         string
	ProductName         string
	CoinAmount          int64
	USDMinorAmount      int64
	ProviderCode        string
	PaymentMethodID     int64
	CountryCode         string
	CurrencyCode        string
	ProviderAmountMinor int64
	PayWay              string
	PayType             string
	PayURL              string
	ProviderOrderID     string
	TxHash              string
	ReceiveAddress      string
	Status              string
	FailureReason       string
	TransactionID       string
	ProviderPayloadJSON string
	CreatedAtMS         int64
	UpdatedAtMS         int64
	IdempotentReplay    bool
}

type CreateExternalRechargeOrderCommand struct {
	AppCode           string
	CommandID         string
	TargetUserID      int64
	TargetRegionID    int64
	TargetCountryCode string
	AudienceType      string
	ProductID         int64
	ProviderCode      string
	PaymentMethodID   int64
	ReturnURL         string
	NotifyURL         string
	ClientIP          string
	Language          string
}

type SubmitExternalRechargeTxCommand struct {
	AppCode      string
	OrderID      string
	TargetUserID int64
	TxHash       string
}

type MifaPayNotification struct {
	MerAccount string
	Data       string
	Sign       string
}

// DiamondExchangeRule 是钻石兑换金币或余额的固定规则投影。
type DiamondExchangeRule struct {
	ExchangeType  string
	FromAssetType string
	ToAssetType   string
	FromAmount    int64
	ToAmount      int64
	Enabled       bool
}

// WalletTransaction 是钱包流水页按用户分录查询的投影。
type WalletTransaction struct {
	EntryID            int64
	TransactionID      string
	BizType            string
	AssetType          string
	AvailableDelta     int64
	FrozenDelta        int64
	AvailableAfter     int64
	FrozenAfter        int64
	CounterpartyUserID int64
	RoomID             string
	CreatedAtMS        int64
}

// ListWalletTransactionsQuery 描述 App 钱包流水分页条件。
type ListWalletTransactionsQuery struct {
	AppCode   string
	UserID    int64
	AssetType string
	Page      int32
	PageSize  int32
}

// VipRewardItem 是 VIP 资源组权益的轻量展示投影。
type VipRewardItem struct {
	ResourceID   int64
	ResourceCode string
	ResourceType string
	Name         string
	Quantity     int64
	ExpiresAtMS  int64
	AssetURL     string
	PreviewURL   string
	AnimationURL string
}

// VipLevel 是可购买 VIP 等级配置。
type VipLevel struct {
	Level                      int32
	Name                       string
	Status                     string
	PriceCoin                  int64
	DurationMS                 int64
	RewardResourceGroupID      int64
	RequiredRechargeCoinAmount int64
	UserRechargeCoinAmount     int64
	RechargeGateRequired       bool
	PurchaseLockedReason       string
	RewardItems                []VipRewardItem
	CanPurchase                bool
	SortOrder                  int32
	CreatedAtMS                int64
	UpdatedAtMS                int64
}

// UserVip 是用户当前会员状态。是否有效以 ExpiresAtMS 和当前时间判断。
type UserVip struct {
	UserID      int64
	Level       int32
	Name        string
	Active      bool
	StartedAtMS int64
	ExpiresAtMS int64
	UpdatedAtMS int64
}

// PurchaseVipCommand 是 App 购买或升级 VIP 的账务命令。
type PurchaseVipCommand struct {
	AppCode   string
	CommandID string
	UserID    int64
	Level     int32
}

// PurchaseVipReceipt 是购买 VIP 成功后的稳定回执。
type PurchaseVipReceipt struct {
	OrderID          string
	TransactionID    string
	Vip              UserVip
	CoinSpent        int64
	CoinBalanceAfter int64
	RewardItems      []VipRewardItem
}

// CPBreakupFeeCommand 是解除 CP/兄弟/姐妹关系时的专用金币扣费命令。
type CPBreakupFeeCommand struct {
	AppCode        string
	CommandID      string
	UserID         int64
	RelationshipID string
	RelationType   string
	Amount         int64
}

// CPBreakupFeeReceipt 返回解除关系扣费流水和 COIN 账后余额。
type CPBreakupFeeReceipt struct {
	TransactionID    string
	CoinSpent        int64
	CoinBalanceAfter int64
	Balance          AssetBalance
}

// GrantVipCommand 是活动或后台发放 VIP 的统一入口命令。
type GrantVipCommand struct {
	AppCode        string
	CommandID      string
	TargetUserID   int64
	Level          int32
	GrantSource    string
	OperatorUserID int64
	Reason         string
}

// GrantVipReceipt 是赠送 VIP 成功后的稳定回执。
type GrantVipReceipt struct {
	TransactionID string
	Vip           UserVip
	RewardItems   []VipRewardItem
}

// AdminVipLevelCommand 是后台保存 VIP 等级配置的完整事实输入。
type AdminVipLevelCommand struct {
	Level                      int32
	Name                       string
	Status                     string
	PriceCoin                  int64
	DurationMS                 int64
	RewardResourceGroupID      int64
	RequiredRechargeCoinAmount int64
	SortOrder                  int32
}

// AssetBalance 是账户当前可用/冻结余额投影。
type AssetBalance struct {
	AppCode         string
	UserID          int64
	AssetType       string
	AvailableAmount int64
	FrozenAmount    int64
	Version         int64
	UpdatedAtMs     int64
}

// AdminCreditAssetCommand 是后台手动调账的最小审计命令，Amount 为正数入账、负数扣账。
type AdminCreditAssetCommand struct {
	AppCode        string
	CommandID      string
	TargetUserID   int64
	AssetType      string
	Amount         int64
	OperatorUserID int64
	Reason         string
	EvidenceRef    string
}

// TaskRewardCommand 是 activity-service 任务领奖的 COIN 入账命令。
type TaskRewardCommand struct {
	AppCode      string
	CommandID    string
	TargetUserID int64
	Amount       int64
	TaskType     string
	TaskID       string
	CycleKey     string
	Reason       string
}

// TaskRewardReceipt 是任务奖励入账后的稳定回执。
type TaskRewardReceipt struct {
	TransactionID string
	Balance       AssetBalance
	Amount        int64
	GrantedAtMS   int64
}

// LuckyGiftRewardCommand 是 activity-service 用抽奖 draw_id 发起的 COIN 入账命令。
type LuckyGiftRewardCommand struct {
	AppCode         string
	CommandID       string
	TargetUserID    int64
	Amount          int64
	DrawID          string
	RoomID          string
	VisibleRegionID int64
	GiftID          string
	PoolID          string
	Reason          string
}

// LuckyGiftRewardReceipt 是幸运礼物返奖入账后的稳定回执。
type LuckyGiftRewardReceipt struct {
	TransactionID string
	Balance       AssetBalance
	Amount        int64
	GrantedAtMS   int64
}

// RoomTurnoverRewardCommand 是 activity-service 每周房间流水奖励的 COIN 入账命令。
type RoomTurnoverRewardCommand struct {
	AppCode       string
	CommandID     string
	TargetUserID  int64
	Amount        int64
	SettlementID  string
	RoomID        string
	PeriodStartMS int64
	PeriodEndMS   int64
	CoinSpent     int64
	TierID        int64
	TierCode      string
	Reason        string
}

// RoomTurnoverRewardReceipt 是房间流水奖励入账后的稳定回执。
type RoomTurnoverRewardReceipt struct {
	TransactionID string
	Balance       AssetBalance
	Amount        int64
	GrantedAtMS   int64
}

// InviteActivityRewardCommand 是 activity-service 邀请活动领奖的 COIN 入账命令。
type InviteActivityRewardCommand struct {
	AppCode      string
	CommandID    string
	TargetUserID int64
	Amount       int64
	ClaimID      string
	RewardType   string
	TierID       int64
	TierCode     string
	CycleKey     string
	ReachedValue int64
	Reason       string
}

// InviteActivityRewardReceipt 是邀请活动奖励入账后的稳定回执。
type InviteActivityRewardReceipt struct {
	TransactionID string
	Balance       AssetBalance
	Amount        int64
	GrantedAtMS   int64
}

// GameCoinChangeCommand 是 game-service 对钱包发起的游戏专用金币改账命令。
type GameCoinChangeCommand struct {
	AppCode         string
	CommandID       string
	UserID          int64
	PlatformCode    string
	GameID          string
	ProviderOrderID string
	ProviderRoundID string
	OpType          string
	CoinAmount      int64
	RoomID          string
	RequestHash     string
}

// GameCoinChangeReceipt 是游戏改账成功或幂等重放后的稳定回执。
type GameCoinChangeReceipt struct {
	TransactionID    string
	BalanceAfter     int64
	IdempotentReplay bool
}

// RedPacketConfig 是后台红包配置的服务端事实，发送路径必须由 wallet-service 强校验。
type RedPacketConfig struct {
	AppCode            string
	Enabled            bool
	CountTiers         []int32
	AmountTiers        []int64
	DelayedOpenSeconds int32
	ExpireSeconds      int32
	DailySendLimit     int32
	UpdatedByAdminID   int64
	RuleURL            string
	CreatedAtMS        int64
	UpdatedAtMS        int64
}

// RedPacket 是红包资金池和状态的只读投影。
type RedPacket struct {
	AppCode           string
	PacketID          string
	CommandID         string
	SenderUserID      int64
	RoomID            string
	RegionID          int64
	PacketType        string
	TotalAmount       int64
	PacketCount       int32
	RemainingAmount   int64
	RemainingCount    int32
	Status            string
	OpenAtMS          int64
	ExpiresAtMS       int64
	CreatedAtMS       int64
	UpdatedAtMS       int64
	ClaimedByViewer   bool
	ViewerClaimAmount int64
	Claims            []RedPacketClaim
	RefundAmount      int64
	RefundStatus      string
	RefundedAtMS      int64
}

// RedPacketClaim 是单个用户抢红包的到账事实。
type RedPacketClaim struct {
	AppCode             string
	ClaimID             string
	CommandID           string
	PacketID            string
	UserID              int64
	Amount              int64
	WalletTransactionID string
	Status              string
	FailureReason       string
	CreatedAtMS         int64
	UpdatedAtMS         int64
}

type RedPacketCreateCommand struct {
	AppCode      string
	CommandID    string
	SenderUserID int64
	RoomID       string
	RegionID     int64
	PacketType   string
	TotalAmount  int64
	PacketCount  int32
}

type RedPacketCreateReceipt struct {
	Packet       RedPacket
	BalanceAfter int64
}

type RedPacketClaimCommand struct {
	AppCode   string
	CommandID string
	PacketID  string
	UserID    int64
}

type RedPacketClaimReceipt struct {
	Claim        RedPacketClaim
	Packet       RedPacket
	BalanceAfter int64
}

type RedPacketRefundReceipt struct {
	Packet         RedPacket
	RefundedAmount int64
}

type RedPacketQuery struct {
	AppCode      string
	RoomID       string
	SenderUserID int64
	RegionID     int64
	PacketType   string
	Status       string
	ViewerUserID int64
	StartAtMS    int64
	EndAtMS      int64
	Page         int32
	PageSize     int32
}

type RedPacketExpireResult struct {
	ExpiredCount   int32
	RefundedAmount int64
}

// ValidAssetType 限定账本允许落账的资产类型，避免写入任意字符串资产。
func ValidAssetType(assetType string) bool {
	switch assetType {
	case AssetCoin, AssetCoinSellerCoin, AssetGiftPoint, AssetHostSalaryUSD, AssetAgencySalaryUSD, AssetBDSalaryUSD, AssetAdminSalaryUSD:
		return true
	default:
		return false
	}
}

// ValidSalaryAssetType 只允许身份工资美元钱包进入工资兑换和转币商链路，避免普通金币或币商库存被误扣。
func ValidSalaryAssetType(assetType string) bool {
	switch strings.ToUpper(strings.TrimSpace(assetType)) {
	case AssetHostSalaryUSD, AssetAgencySalaryUSD, AssetBDSalaryUSD, AssetAdminSalaryUSD:
		return true
	default:
		return false
	}
}

func NormalizeGiftChargeAssetType(assetType string) string {
	return AssetCoin
}

func NormalizeVipGrantSource(source string) string {
	switch strings.ToLower(strings.TrimSpace(source)) {
	case VipGrantSourcePurchase:
		return VipGrantSourcePurchase
	case VipGrantSourceActivity:
		return VipGrantSourceActivity
	case VipGrantSourceAdmin:
		return VipGrantSourceAdmin
	case VipGrantSourceManagerCenter:
		return VipGrantSourceManagerCenter
	default:
		return ""
	}
}

func ValidGiftChargeAssetType(assetType string) bool {
	switch strings.ToUpper(strings.TrimSpace(assetType)) {
	case AssetCoin:
		return true
	default:
		return false
	}
}

func NormalizeCoinSellerStockType(stockType string) string {
	switch strings.ToLower(strings.TrimSpace(stockType)) {
	case StockTypeUSDTPurchase:
		return StockTypeUSDTPurchase
	case StockTypeCoinCompensation:
		return StockTypeCoinCompensation
	default:
		return ""
	}
}

func NormalizeRechargeProductStatus(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case RechargeProductStatusActive:
		return RechargeProductStatusActive
	case RechargeProductStatusDisabled:
		return RechargeProductStatusDisabled
	default:
		return ""
	}
}

func NormalizeRechargeProductPlatform(platform string) string {
	switch strings.ToLower(strings.TrimSpace(platform)) {
	case RechargeProductPlatformAndroid:
		return RechargeProductPlatformAndroid
	case RechargeProductPlatformIOS:
		return RechargeProductPlatformIOS
	case RechargeProductPlatformWeb:
		return RechargeProductPlatformWeb
	default:
		return ""
	}
}

func RechargeChannelForPlatform(platform string) string {
	switch NormalizeRechargeProductPlatform(platform) {
	case RechargeProductPlatformAndroid:
		return RechargeChannelGoogle
	case RechargeProductPlatformIOS:
		return RechargeChannelApple
	case RechargeProductPlatformWeb:
		return RechargeChannelExternal
	default:
		return ""
	}
}

func NormalizeRechargeAudienceType(audienceType string) string {
	switch strings.ToLower(strings.TrimSpace(audienceType)) {
	case "", RechargeAudienceNormal:
		return RechargeAudienceNormal
	case RechargeAudienceCoinSeller:
		return RechargeAudienceCoinSeller
	default:
		return ""
	}
}

func NormalizePaymentProvider(provider string) string {
	switch strings.ToLower(strings.TrimSpace(provider)) {
	case PaymentProviderMifaPay:
		return PaymentProviderMifaPay
	case PaymentProviderUSDTTRC20:
		return PaymentProviderUSDTTRC20
	case PaymentProviderGooglePlay:
		return PaymentProviderGooglePlay
	default:
		return ""
	}
}

func NormalizeThirdPartyPaymentStatus(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case ThirdPartyPaymentStatusActive:
		return ThirdPartyPaymentStatusActive
	case ThirdPartyPaymentStatusDisabled:
		return ThirdPartyPaymentStatusDisabled
	default:
		return ""
	}
}

func NormalizeExternalRechargeStatus(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case ExternalRechargeStatusPending:
		return ExternalRechargeStatusPending
	case ExternalRechargeStatusRedirected:
		return ExternalRechargeStatusRedirected
	case ExternalRechargeStatusCredited:
		return ExternalRechargeStatusCredited
	case ExternalRechargeStatusFailed:
		return ExternalRechargeStatusFailed
	default:
		return ""
	}
}

func NormalizeGameOpType(opType string) string {
	switch strings.ToLower(strings.TrimSpace(opType)) {
	case GameOpDebit:
		return GameOpDebit
	case GameOpCredit:
		return GameOpCredit
	case GameOpRefund:
		return GameOpRefund
	case GameOpReverse:
		return GameOpReverse
	default:
		return ""
	}
}

func NormalizeRedPacketType(packetType string) string {
	switch strings.ToUpper(strings.TrimSpace(packetType)) {
	case "IMMEDIATE":
		return RedPacketTypeNormal
	case "DELAYED":
		return RedPacketTypeDelayed
	}
	switch strings.ToLower(strings.TrimSpace(packetType)) {
	case RedPacketTypeNormal:
		return RedPacketTypeNormal
	case RedPacketTypeDelayed:
		return RedPacketTypeDelayed
	default:
		return ""
	}
}

func NormalizeRedPacketStatus(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case RedPacketStatusWaitingOpen:
		return RedPacketStatusWaitingOpen
	case RedPacketStatusActive:
		return RedPacketStatusActive
	case RedPacketStatusFinished:
		return RedPacketStatusFinished
	case RedPacketStatusRefunded:
		return RedPacketStatusRefunded
	default:
		return ""
	}
}
