package wallet

import (
	"context"
	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	"hyapp/services/wallet-service/internal/domain/ledger"
	"strings"
)

// ListThirdPartyPaymentChannels 返回后台三方支付管理页需要的渠道、国家和方式树。
func (s *Service) ListThirdPartyPaymentChannels(ctx context.Context, query ledger.ListThirdPartyPaymentChannelsQuery) ([]ledger.ThirdPartyPaymentChannel, error) {
	if s.repository == nil {
		return nil, xerr.New(xerr.Unavailable, "wallet repository is not configured")
	}
	query.AppCode = appcode.Normalize(query.AppCode)
	if strings.TrimSpace(query.Status) != "" {
		query.Status = ledger.NormalizeThirdPartyPaymentStatus(query.Status)
		if query.Status == "" {
			return nil, xerr.New(xerr.InvalidArgument, "status is invalid")
		}
	}
	ctx = appcode.WithContext(ctx, query.AppCode)
	return s.repository.ListThirdPartyPaymentChannels(ctx, query)
}

func (s *Service) SetThirdPartyPaymentMethodStatus(ctx context.Context, command ledger.ThirdPartyPaymentMethodStatusCommand) (ledger.ThirdPartyPaymentMethod, error) {
	if command.MethodID <= 0 || command.OperatorUserID <= 0 {
		return ledger.ThirdPartyPaymentMethod{}, xerr.New(xerr.InvalidArgument, "payment method and operator are required")
	}
	if s.repository == nil {
		return ledger.ThirdPartyPaymentMethod{}, xerr.New(xerr.Unavailable, "wallet repository is not configured")
	}
	command.AppCode = appcode.Normalize(command.AppCode)
	ctx = appcode.WithContext(ctx, command.AppCode)
	return s.repository.SetThirdPartyPaymentMethodStatus(ctx, command)
}

func (s *Service) UpdateThirdPartyPaymentRate(ctx context.Context, command ledger.ThirdPartyPaymentRateCommand) (ledger.ThirdPartyPaymentMethod, error) {
	command.AppCode = appcode.Normalize(command.AppCode)
	command.USDToCurrencyRate = strings.TrimSpace(command.USDToCurrencyRate)
	if command.MethodID <= 0 || command.OperatorUserID <= 0 || !validNonNegativeDecimal(command.USDToCurrencyRate) {
		return ledger.ThirdPartyPaymentMethod{}, xerr.New(xerr.InvalidArgument, "payment rate command is invalid")
	}
	if s.repository == nil {
		return ledger.ThirdPartyPaymentMethod{}, xerr.New(xerr.Unavailable, "wallet repository is not configured")
	}
	ctx = appcode.WithContext(ctx, command.AppCode)
	return s.repository.UpdateThirdPartyPaymentRate(ctx, command)
}

// ListH5RechargeOptions 只返回目标用户当前可买商品和已配置汇率的支付方式。
func (s *Service) ListH5RechargeOptions(ctx context.Context, query ledger.H5RechargeOptionsQuery) (ledger.H5RechargeOptions, error) {
	query.AppCode = appcode.Normalize(query.AppCode)
	query.AudienceType = ledger.NormalizeRechargeAudienceType(query.AudienceType)
	query.TargetCountryCode = strings.ToUpper(strings.TrimSpace(query.TargetCountryCode))
	if query.TargetUserID <= 0 || query.TargetRegionID <= 0 || query.AudienceType == "" {
		return ledger.H5RechargeOptions{}, xerr.New(xerr.InvalidArgument, "h5 recharge options query is incomplete")
	}
	if s.repository == nil {
		return ledger.H5RechargeOptions{}, xerr.New(xerr.Unavailable, "wallet repository is not configured")
	}
	ctx = appcode.WithContext(ctx, query.AppCode)
	options, err := s.repository.ListH5RechargeOptions(ctx, query)
	if err != nil {
		return ledger.H5RechargeOptions{}, err
	}
	if s.mifaPay == nil && s.v5Pay == nil {
		options.PaymentMethods = nil
	} else {
		filtered := options.PaymentMethods[:0]
		for _, method := range options.PaymentMethods {

			if method.ProviderCode == ledger.PaymentProviderMifaPay && s.mifaPay != nil {
				filtered = append(filtered, method)
			}
			if method.ProviderCode == ledger.PaymentProviderV5Pay && s.v5Pay != nil {
				filtered = append(filtered, method)
			}
		}
		options.PaymentMethods = s.filterV5PayRuntimeProductTypes(ctx, filtered)
	}
	options.USDTTRC20Enabled = s.externalRecharge.USDTTRC20Enabled && s.externalRecharge.USDTTRC20Address != ""
	options.USDTTRC20Address = s.externalRecharge.USDTTRC20Address
	return options, nil
}

func (s *Service) filterV5PayRuntimeProductTypes(ctx context.Context, methods []ledger.ThirdPartyPaymentMethod) []ledger.ThirdPartyPaymentMethod {
	if s.v5Pay == nil || len(methods) == 0 {
		return methods
	}
	type productKey struct {
		country  string
		currency string
	}
	allowedByKey := map[productKey]map[string]bool{}
	filtered := methods[:0]
	for _, method := range methods {
		if method.ProviderCode != ledger.PaymentProviderV5Pay {
			filtered = append(filtered, method)
			continue
		}
		key := productKey{country: strings.ToUpper(strings.TrimSpace(method.CountryCode)), currency: strings.ToUpper(strings.TrimSpace(method.CurrencyCode))}
		allowed, ok := allowedByKey[key]
		if !ok {
			allowed = map[string]bool{}
			products, err := s.v5Pay.ListProductTypes(ctx, V5PayProductTypesRequest{CountryCode: key.country, CurrencyCode: key.currency})
			if err == nil {
				for _, product := range products.PayinList {

					if product.SupportCashierMode == 0 {
						continue
					}
					if product.Currency != "" && !strings.EqualFold(product.Currency, key.currency) {
						continue
					}
					if productType := strings.ToUpper(strings.TrimSpace(product.ProductType)); productType != "" {
						allowed[productType] = true
					}
				}
			}
			allowedByKey[key] = allowed
		}
		if allowed[strings.ToUpper(strings.TrimSpace(method.PayType))] {
			filtered = append(filtered, method)
		}
	}
	return filtered
}
