package orchestrator

import (
	"strings"

	"github.com/shopspring/decimal"
	"github.com/tech/sendico/payments/orchestrator/storage/model"
	paymenttypes "github.com/tech/sendico/pkg/payments/types"
)

func ensureExecutionPlan(payment *model.Payment) *model.ExecutionPlan {
	if payment == nil {
		return nil
	}
	if payment.ExecutionPlan == nil {
		payment.ExecutionPlan = &model.ExecutionPlan{}
	}
	return payment.ExecutionPlan
}

func ensureExecutionStep(plan *model.ExecutionPlan, code string) *model.ExecutionStep {
	if plan == nil {
		return nil
	}
	code = strings.TrimSpace(code)
	if code == "" {
		return nil
	}
	for _, step := range plan.Steps {
		if step == nil {
			continue
		}
		if strings.EqualFold(step.Code, code) {
			if step.Code == "" {
				step.Code = code
			}
			return step
		}
	}
	step := &model.ExecutionStep{Code: code}
	plan.Steps = append(plan.Steps, step)
	return step
}

func updateExecutionPlanTotalNetworkFee(plan *model.ExecutionPlan) {
	if plan == nil {
		return
	}
	total := decimal.Zero
	currency := ""
	hasFee := false
	for _, step := range plan.Steps {
		if step == nil || step.NetworkFee == nil {
			continue
		}
		fee := step.NetworkFee
		if strings.TrimSpace(fee.GetAmount()) == "" || strings.TrimSpace(fee.GetCurrency()) == "" {
			continue
		}
		if currency == "" {
			currency = strings.TrimSpace(fee.GetCurrency())
		} else if !strings.EqualFold(currency, fee.GetCurrency()) {
			continue
		}
		value, err := decimalFromMoney(fee)
		if err != nil {
			continue
		}
		total = total.Add(value)
		hasFee = true
	}
	if !hasFee || currency == "" {
		plan.TotalNetworkFee = nil
		return
	}
	plan.TotalNetworkFee = &paymenttypes.Money{
		Currency: currency,
		Amount:   total.String(),
	}
}
