package payment

import (
	"fmt"
	"strconv"
	"strings"

	walletv1 "hyapp.local/api/proto/wallet/v1"
)

type rechargeBillDTO struct {
	AppCode                string `json:"appCode"`
	TransactionID          string `json:"transactionId"`
	CommandID              string `json:"commandId"`
	RechargeType           string `json:"rechargeType"`
	Status                 string `json:"status"`
	ExternalRef            string `json:"externalRef"`
	UserID                 int64  `json:"userId"`
	SellerUserID           int64  `json:"sellerUserId"`
	SellerRegionID         int64  `json:"sellerRegionId"`
	TargetRegionID         int64  `json:"targetRegionId"`
	PolicyID               int64  `json:"policyId"`
	PolicyVersion          string `json:"policyVersion"`
	CurrencyCode           string `json:"currencyCode"`
	CoinAmount             int64  `json:"coinAmount"`
	USDMinorAmount         int64  `json:"usdMinorAmount"`
	ExchangeCoinAmount     int64  `json:"exchangeCoinAmount"`
	ExchangeUSDMinorAmount int64  `json:"exchangeUsdMinorAmount"`
	CreatedAtMS            int64  `json:"createdAtMs"`
}

type rechargeProductDTO struct {
	AppCode           string  `json:"appCode"`
	ProductID         int64   `json:"productId"`
	ProductCode       string  `json:"productCode"`
	ProductName       string  `json:"productName"`
	Description       string  `json:"description"`
	Platform          string  `json:"platform"`
	Channel           string  `json:"channel"`
	CurrencyCode      string  `json:"currencyCode"`
	AmountUSDT        string  `json:"amountUsdt"`
	AmountUSDTMicro   int64   `json:"amountUsdtMicro"`
	AmountMicro       int64   `json:"amountMicro"`
	AmountMinor       int64   `json:"amountMinor"`
	CoinAmount        int64   `json:"coinAmount"`
	PolicyVersion     string  `json:"policyVersion"`
	RegionIDs         []int64 `json:"regionIds"`
	ResourceAssetType string  `json:"resourceAssetType"`
	Status            string  `json:"status"`
	Enabled           bool    `json:"enabled"`
	SortOrder         int32   `json:"sortOrder"`
	CreatedByUserID   int64   `json:"createdByUserId"`
	UpdatedByUserID   int64   `json:"updatedByUserId"`
	CreatedAtMS       int64   `json:"createdAtMs"`
	UpdatedAtMS       int64   `json:"updatedAtMs"`
}

func rechargeBillFromProto(item *walletv1.RechargeBill) rechargeBillDTO {
	if item == nil {
		return rechargeBillDTO{}
	}
	return rechargeBillDTO{
		AppCode:                item.GetAppCode(),
		TransactionID:          item.GetTransactionId(),
		CommandID:              item.GetCommandId(),
		RechargeType:           item.GetRechargeType(),
		Status:                 item.GetStatus(),
		ExternalRef:            item.GetExternalRef(),
		UserID:                 item.GetUserId(),
		SellerUserID:           item.GetSellerUserId(),
		SellerRegionID:         item.GetSellerRegionId(),
		TargetRegionID:         item.GetTargetRegionId(),
		PolicyID:               item.GetPolicyId(),
		PolicyVersion:          item.GetPolicyVersion(),
		CurrencyCode:           item.GetCurrencyCode(),
		CoinAmount:             item.GetCoinAmount(),
		USDMinorAmount:         item.GetUsdMinorAmount(),
		ExchangeCoinAmount:     item.GetExchangeCoinAmount(),
		ExchangeUSDMinorAmount: item.GetExchangeUsdMinorAmount(),
		CreatedAtMS:            item.GetCreatedAtMs(),
	}
}

func rechargeProductFromProto(item *walletv1.RechargeProduct) rechargeProductDTO {
	if item == nil {
		return rechargeProductDTO{}
	}
	return rechargeProductDTO{
		AppCode:           item.GetAppCode(),
		ProductID:         item.GetProductId(),
		ProductCode:       item.GetProductCode(),
		ProductName:       item.GetProductName(),
		Description:       item.GetDescription(),
		Platform:          item.GetPlatform(),
		Channel:           item.GetChannel(),
		CurrencyCode:      item.GetCurrencyCode(),
		AmountUSDT:        formatUSDTMicro(item.GetAmountMicro()),
		AmountUSDTMicro:   item.GetAmountMicro(),
		AmountMicro:       item.GetAmountMicro(),
		AmountMinor:       item.GetAmountMinor(),
		CoinAmount:        item.GetCoinAmount(),
		PolicyVersion:     item.GetPolicyVersion(),
		RegionIDs:         append([]int64(nil), item.GetRegionIds()...),
		ResourceAssetType: item.GetResourceAssetType(),
		Status:            item.GetStatus(),
		Enabled:           item.GetEnabled(),
		SortOrder:         item.GetSortOrder(),
		CreatedByUserID:   item.GetCreatedByUserId(),
		UpdatedByUserID:   item.GetUpdatedByUserId(),
		CreatedAtMS:       item.GetCreatedAtMs(),
		UpdatedAtMS:       item.GetUpdatedAtMs(),
	}
}

func formatUSDTMicro(amount int64) string {
	if amount <= 0 {
		return "0"
	}
	whole := amount / usdtMicroUnit
	fraction := amount % usdtMicroUnit
	if fraction == 0 {
		return strconv.FormatInt(whole, 10)
	}
	return fmt.Sprintf("%d.%s", whole, strings.TrimRight(fmt.Sprintf("%06d", fraction), "0"))
}
