package ledger

import (
	"strings"
)

// 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
	AppVisible        bool
	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
	AppVisible     *bool
	OperatorUserID int64
}

// GooglePaymentCommand 是 App 完成 Google Play 支付后提交给后端确认和入账的命令。
type GooglePaymentCommand struct {
	AppCode        string
	CommandID      string
	UserID         int64
	RegionID       int64
	CountryID      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
}

// GooglePlayOrder 是 Play Developer API Orders 接口返回的订单实付快照；金额统一收敛为实付币种微单位。
type GooglePlayOrder struct {
	OrderID          string
	State            string
	BuyerCountry     string
	CurrencyCode     string
	TotalAmountMicro int64
	TaxAmountMicro   int64
	// NetAmountMicro 是 Google 扣除服务费和代缴税后的开发者净收入（实付币种）；接口未返回时为 0。
	NetAmountMicro int64
	RawJSON        string
}

// GooglePaymentPaidDetails 是写回 payment_orders 的实付明细命令。
type GooglePaymentPaidDetails struct {
	CurrencyCode    string
	PaidAmountMicro int64
	TaxAmountMicro  int64
	NetAmountMicro  int64
	SyncedAtMS      int64
}

// GooglePaymentOrderRef 是按钱包交易反查 Google 支付订单、发起 Orders API 查询所需的最小定位信息。
type GooglePaymentOrderRef struct {
	AppCode          string
	PaymentOrderID   string
	TransactionID    string
	PackageName      string
	ProviderOrderID  string
	PaidSyncedAtMS   int64
	SyncAttemptCount int
}

// 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
}

// ThirdPartyPaymentMethodSyncCommand 表示后台要求 wallet-service 从支付商实时拉取可用方式并同步到本地配置表。
type ThirdPartyPaymentMethodSyncCommand struct {
	AppCode        string
	ProviderCode   string
	OperatorUserID int64
}

// ThirdPartyPaymentMethodSyncIssue 记录某个国家/币种同步失败或被支付商拒绝的原因；同步整体可部分成功。
type ThirdPartyPaymentMethodSyncIssue struct {
	CountryCode  string
	CurrencyCode string
	Code         string
	Message      string
}

// ThirdPartyPaymentMethodSyncResult 是同步操作的可审计摘要，避免后台只知道请求成功却不知道实际写入了什么。
type ThirdPartyPaymentMethodSyncResult struct {
	ProviderCode        string
	ScannedCountryCount int
	FetchedCountryCount int
	CreatedCount        int
	UpdatedCount        int
	SkippedCount        int
	Issues              []ThirdPartyPaymentMethodSyncIssue
}

// 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
}

// VerifyCoinSellerRechargeReceiptCommand 是运营提交的币商充值凭证查询条件；校验只读，不创建订单、不入账。
type VerifyCoinSellerRechargeReceiptCommand struct {
	RequestID            string
	AppCode              string
	ProviderCode         string
	ExternalOrderNo      string
	Chain                string
	USDMinorAmount       int64
	OrderDateMS          int64
	ProviderCountryCode  string
	ProviderCurrencyCode string
	ProviderAmountMinor  int64
	ProviderPayType      string
	// ReceiveAddress 只接受内部 admin-server 传入的当前 SQL 配置；为空时保留 H5/YAML 兼容路径。
	ReceiveAddress string
}

// CoinSellerRechargeReceiptVerification 是三方或链上返回的只读凭证快照。
type CoinSellerRechargeReceiptVerification struct {
	Verified            bool
	ProviderCode        string
	ExternalOrderNo     string
	ProviderOrderID     string
	Status              string
	CurrencyCode        string
	ProviderAmountMinor int64
	RawJSON             string
	Chain               string
	ReceiveAddress      string
	VerifiedAtMS        int64
	FailureReason       string
}

// ListTemporaryExternalRechargeOrdersQuery 是后台临时支付链接列表的筛选条件。
type ListTemporaryExternalRechargeOrdersQuery struct {
	AppCode      string
	Status       string
	ProviderCode string
	Keyword      string
	Page         int32
	PageSize     int32
}

// ExternalRechargeOrder 保存 H5 外部充值订单的订单、支付和入账状态。
type ExternalRechargeOrder struct {
	OrderID             string
	AppCode             string
	CommandID           string
	TargetUserID        int64
	TargetRegionID      int64
	TargetCountryID     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
	TargetCountryID   int64
	TargetCountryCode string
	AudienceType      string
	ProductID         int64
	ProviderCode      string
	PaymentMethodID   int64
	ReturnURL         string
	NotifyURL         string
	ClientIP          string
	Language          string
	PayerName         string
	PayerAccount      string
	PayerEmail        string
}

// CreateTemporaryExternalRechargeOrderCommand 是运营临时收款链接的下单快照。
// 这类订单没有充值目标用户和商品档位，支付成功后只保留 paid 状态，金币由运营线下核销。
type CreateTemporaryExternalRechargeOrderCommand struct {
	AppCode         string
	CommandID       string
	CoinAmount      int64
	USDMinorAmount  int64
	ProviderCode    string
	PaymentMethodID int64
	ReturnURL       string
	NotifyURL       string
	ClientIP        string
	Language        string
	PayerName       string
	PayerAccount    string
	PayerEmail      string
}

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

type MifaPayNotification struct {
	MerAccount string
	Data       string
	Sign       string
}

// V5PayNotification 保存 V5Pay 回调原始字段；验签必须使用所有返回字段，避免未来新增字段绕过签名校验。
type V5PayNotification struct {
	Fields  map[string]string
	RawJSON string
}

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 PaymentProviderV5Pay:
		return PaymentProviderV5Pay
	case PaymentProviderUSDTTRC20:
		return PaymentProviderUSDTTRC20
	case PaymentProviderUSDTBEP20:
		return PaymentProviderUSDTBEP20
	case PaymentProviderUSDTC2C:
		return PaymentProviderUSDTC2C
	case PaymentProviderUSDTOffchain:
		return PaymentProviderUSDTOffchain
	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 ""
	}
}
