package transfer

import (
	"strings"

	"github.com/shopspring/decimal"
	"github.com/tech/sendico/gateway/tron/shared"
	"github.com/tech/sendico/gateway/tron/storage/model"
	"github.com/tech/sendico/pkg/merrors"
	chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
)

func convertFees(fees []*chainv1.ServiceFeeBreakdown, currency string) ([]model.ServiceFee, decimal.Decimal, error) {
	result := make([]model.ServiceFee, 0, len(fees))
	sum := decimal.NewFromInt(0)
	for _, fee := range fees {
		if fee == nil || fee.GetAmount() == nil {
			return nil, decimal.Decimal{}, merrors.InvalidArgument("fee amount is required")
		}
		amtCurrency := strings.ToUpper(strings.TrimSpace(fee.GetAmount().GetCurrency()))
		if amtCurrency != strings.ToUpper(currency) {
			return nil, decimal.Decimal{}, merrors.InvalidArgument("fee currency mismatch")
		}
		amtValue := strings.TrimSpace(fee.GetAmount().GetAmount())
		if amtValue == "" {
			return nil, decimal.Decimal{}, merrors.InvalidArgument("fee amount is required")
		}
		dec, err := decimal.NewFromString(amtValue)
		if err != nil {
			return nil, decimal.Decimal{}, merrors.InvalidArgument("invalid fee amount")
		}
		if dec.IsNegative() {
			return nil, decimal.Decimal{}, merrors.InvalidArgument("fee amount must be non-negative")
		}
		sum = sum.Add(dec)
		result = append(result, model.ServiceFee{
			FeeCode:     strings.TrimSpace(fee.GetFeeCode()),
			Amount:      shared.CloneMoney(fee.GetAmount()),
			Description: strings.TrimSpace(fee.GetDescription()),
		})
	}
	return result, sum, nil
}
