package orchestrator

import (
	"strings"

	"github.com/shopspring/decimal"
	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrationv2/agg"
	svcshared "github.com/tech/sendico/payments/orchestrator/internal/service/shared"
	paymenttypes "github.com/tech/sendico/pkg/payments/types"
	moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
	chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
)

var cardMinorUnitScale = decimal.NewFromInt(100)

func protoMoneyToPaymentMoney(src *moneyv1.Money) *paymenttypes.Money {
	if src == nil {
		return nil
	}
	amount := strings.TrimSpace(src.GetAmount())
	currency := strings.TrimSpace(src.GetCurrency())
	if amount == "" || currency == "" {
		return nil
	}
	return &paymenttypes.Money{Amount: amount, Currency: currency}
}

func paymentMoneyToProto(src *paymenttypes.Money) *moneyv1.Money {
	if src == nil {
		return nil
	}
	amount := strings.TrimSpace(src.GetAmount())
	currency := strings.TrimSpace(src.GetCurrency())
	if amount == "" || currency == "" {
		return nil
	}
	return &moneyv1.Money{Amount: amount, Currency: currency}
}

func plannedStepMoney(step agg.StepExecution) *paymenttypes.Money {
	return svcshared.CloneMoneyTrimNonEmpty(step.PlannedMoney)
}

func plannedStepConvertedMoney(step agg.StepExecution) *paymenttypes.Money {
	return svcshared.CloneMoneyTrimNonEmpty(step.PlannedConvertedMoney)
}

func transferExecutedMoney(transfer *chainv1.Transfer) *paymenttypes.Money {
	if transfer == nil {
		return nil
	}
	if money := protoMoneyToPaymentMoney(transfer.GetNetAmount()); money != nil {
		return money
	}
	return protoMoneyToPaymentMoney(transfer.GetRequestedAmount())
}

func cardMinorToMoney(amountMinor int64, currency string) *paymenttypes.Money {
	currency = strings.ToUpper(strings.TrimSpace(currency))
	if idx := strings.Index(currency, "-"); idx > 0 {
		currency = currency[:idx]
	}
	if currency == "" {
		return nil
	}
	amount := decimal.NewFromInt(amountMinor).Div(cardMinorUnitScale)
	return &paymenttypes.Money{
		Amount:   amount.StringFixed(2),
		Currency: currency,
	}
}
