package serverimp

import (
	"strings"

	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
	"github.com/tech/sendico/pkg/discovery"
	"github.com/tech/sendico/pkg/mlogger"
)

func buildCardGatewayRoutes(src map[string]cardGatewayRouteConfig) map[string]orchestrator.CardGatewayRoute {
	if len(src) == 0 {
		return nil
	}
	result := make(map[string]orchestrator.CardGatewayRoute, len(src))
	for key, route := range src {
		trimmedKey := strings.TrimSpace(key)
		if trimmedKey == "" {
			continue
		}
		result[trimmedKey] = orchestrator.CardGatewayRoute{
			FundingAddress: strings.TrimSpace(route.FundingAddress),
			FeeAddress:     strings.TrimSpace(route.FeeAddress),
			FeeWalletRef:   strings.TrimSpace(route.FeeWalletRef),
		}
	}
	return result
}

func buildFeeLedgerAccounts(src map[string]string) map[string]string {
	if len(src) == 0 {
		return nil
	}
	result := make(map[string]string, len(src))
	for key, account := range src {
		k := strings.ToLower(strings.TrimSpace(key))
		v := strings.TrimSpace(account)
		if k == "" || v == "" {
			continue
		}
		result[k] = v
	}
	return result
}

func buildGatewayRegistry(logger mlogger.Logger, src []gatewayInstanceConfig, registry *discovery.Registry) orchestrator.GatewayRegistry {
	if logger != nil {
		logger = logger.Named("gateway_registry")
	}
	if len(src) > 0 && logger != nil {
		logger.Warn("Static gateway configuration ignored; using discovery registry only")
	}
	if registry == nil {
		if logger != nil {
			logger.Warn("Discovery registry unavailable; gateway routing disabled")
		}
		return nil
	}
	return orchestrator.NewDiscoveryGatewayRegistry(logger, registry)
}
