package orchestrator

import (
	"context"
	"sort"
	"strings"

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

func ensureGatewayForAction(ctx context.Context, registry GatewayRegistry, cache map[model.Rail]*model.GatewayInstanceDescriptor, rail model.Rail, network string, amount *paymenttypes.Money, action model.RailOperation, instanceID string, dir sendDirection) (*model.GatewayInstanceDescriptor, error) {
	if registry == nil {
		return nil, merrors.InvalidArgument("plan builder: gateway registry is required")
	}
	if gw, ok := cache[rail]; ok && gw != nil {
		if instanceID == "" || strings.EqualFold(gw.InstanceID, instanceID) {
			if err := validateGatewayAction(gw, network, amount, action, dir); err != nil {
				return nil, err
			}
			return gw, nil
		}
	}
	gw, err := selectGateway(ctx, registry, rail, network, amount, action, instanceID, dir)
	if err != nil {
		return nil, err
	}
	cache[rail] = gw
	return gw, nil
}

func validateGatewayAction(gw *model.GatewayInstanceDescriptor, network string, amount *paymenttypes.Money, action model.RailOperation, dir sendDirection) error {
	if gw == nil {
		return merrors.InvalidArgument("plan builder: gateway instance is required")
	}
	currency := ""
	amt := decimal.Zero
	if amount != nil && strings.TrimSpace(amount.GetAmount()) != "" {
		value, err := decimalFromMoney(amount)
		if err != nil {
			return err
		}
		amt = value
		currency = strings.ToUpper(strings.TrimSpace(amount.GetCurrency()))
	}
	if !isGatewayEligible(gw, gw.Rail, network, currency, action, dir, amt) {
		return merrors.InvalidArgument("plan builder: gateway instance is not eligible")
	}
	return nil
}

type sendDirection int

const (
	sendDirectionAny sendDirection = iota
	sendDirectionOut
	sendDirectionIn
)

func sendDirectionForRail(rail model.Rail) sendDirection {
	switch rail {
	case model.RailFiatOnRamp:
		return sendDirectionIn
	default:
		return sendDirectionOut
	}
}

func selectGateway(ctx context.Context, registry GatewayRegistry, rail model.Rail, network string, amount *paymenttypes.Money, action model.RailOperation, instanceID string, dir sendDirection) (*model.GatewayInstanceDescriptor, error) {
	if registry == nil {
		return nil, merrors.InvalidArgument("plan builder: gateway registry is required")
	}
	all, err := registry.List(ctx)
	if err != nil {
		return nil, err
	}
	if len(all) == 0 {
		return nil, merrors.InvalidArgument("plan builder: no gateway instances available")
	}

	currency := ""
	amt := decimal.Zero
	if amount != nil && strings.TrimSpace(amount.GetAmount()) != "" {
		amt, err = decimalFromMoney(amount)
		if err != nil {
			return nil, err
		}
		currency = strings.ToUpper(strings.TrimSpace(amount.GetCurrency()))
	}
	network = strings.ToUpper(strings.TrimSpace(network))

	eligible := make([]*model.GatewayInstanceDescriptor, 0)
	for _, gw := range all {
		if instanceID != "" && !strings.EqualFold(strings.TrimSpace(gw.InstanceID), instanceID) {
			continue
		}
		if !isGatewayEligible(gw, rail, network, currency, action, dir, amt) {
			continue
		}
		eligible = append(eligible, gw)
	}
	if len(eligible) == 0 {
		return nil, merrors.InvalidArgument("plan builder: no eligible gateway instance found")
	}
	sort.Slice(eligible, func(i, j int) bool {
		return eligible[i].ID < eligible[j].ID
	})
	return eligible[0], nil
}

func isGatewayEligible(gw *model.GatewayInstanceDescriptor, rail model.Rail, network, currency string, action model.RailOperation, dir sendDirection, amount decimal.Decimal) bool {
	if gw == nil || !gw.IsEnabled {
		return false
	}
	if gw.Rail != rail {
		return false
	}
	if network != "" && gw.Network != "" && !strings.EqualFold(gw.Network, network) {
		return false
	}
	if currency != "" && len(gw.Currencies) > 0 {
		found := false
		for _, c := range gw.Currencies {
			if strings.EqualFold(c, currency) {
				found = true
				break
			}
		}
		if !found {
			return false
		}
	}

	if !capabilityAllowsAction(gw.Capabilities, action, dir) {
		return false
	}

	if currency != "" {
		if !amountWithinLimits(gw.Limits, currency, amount, action) {
			return false
		}
	}
	return true
}

func capabilityAllowsAction(cap model.RailCapabilities, action model.RailOperation, dir sendDirection) bool {
	switch action {
	case model.RailOperationSend:
		switch dir {
		case sendDirectionOut:
			return cap.CanPayOut
		case sendDirectionIn:
			return cap.CanPayIn
		default:
			return cap.CanPayIn || cap.CanPayOut
		}
	case model.RailOperationFee:
		return cap.CanSendFee
	case model.RailOperationObserveConfirm:
		return cap.RequiresObserveConfirm
	case model.RailOperationBlock:
		return cap.CanBlock
	case model.RailOperationRelease:
		return cap.CanRelease
	default:
		return true
	}
}

func amountWithinLimits(limits model.Limits, currency string, amount decimal.Decimal, action model.RailOperation) bool {
	min := firstLimitValue(limits.MinAmount, "")
	max := firstLimitValue(limits.MaxAmount, "")
	perTxMin := firstLimitValue(limits.PerTxMinAmount, "")
	perTxMax := firstLimitValue(limits.PerTxMaxAmount, "")
	maxFee := firstLimitValue(limits.PerTxMaxFee, "")

	if override, ok := limits.CurrencyLimits[currency]; ok {
		min = firstLimitValue(override.MinAmount, min)
		max = firstLimitValue(override.MaxAmount, max)
		if action == model.RailOperationFee {
			maxFee = firstLimitValue(override.MaxFee, maxFee)
		}
	}

	if min != "" {
		if val, err := decimal.NewFromString(min); err == nil && amount.LessThan(val) {
			return false
		}
	}
	if perTxMin != "" {
		if val, err := decimal.NewFromString(perTxMin); err == nil && amount.LessThan(val) {
			return false
		}
	}
	if max != "" {
		if val, err := decimal.NewFromString(max); err == nil && amount.GreaterThan(val) {
			return false
		}
	}
	if perTxMax != "" {
		if val, err := decimal.NewFromString(perTxMax); err == nil && amount.GreaterThan(val) {
			return false
		}
	}
	if action == model.RailOperationFee && maxFee != "" {
		if val, err := decimal.NewFromString(maxFee); err == nil && amount.GreaterThan(val) {
			return false
		}
	}

	return true
}

func firstLimitValue(primary, fallback string) string {
	val := strings.TrimSpace(primary)
	if val != "" {
		return val
	}
	return strings.TrimSpace(fallback)
}
