package serverimp

import (
	ledgerclient "github.com/tech/sendico/ledger/client"
	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
)

type orchestratorDeps struct {
	ledgerClient          ledgerclient.Client
	gatewayInvokeResolver orchestrator.GatewayInvokeResolver
}

func (i *Imp) initDependencies(_ *config) *orchestratorDeps {
	deps := &orchestratorDeps{}
	if i.discoveryReg == nil {
		if i.logger != nil {
			i.logger.Warn("Discovery registry unavailable; downstream clients disabled")
		}
		return deps
	}

	i.discoveryClients = newDiscoveryClientResolver(i.logger, i.discoveryReg)
	deps.ledgerClient = &discoveryLedgerClient{resolver: i.discoveryClients}
	deps.gatewayInvokeResolver = discoveryGatewayInvokeResolver{resolver: i.discoveryClients}
	return deps
}

func (i *Imp) buildServiceOptions(cfg *config, deps *orchestratorDeps) []orchestrator.Option {
	if cfg == nil || deps == nil {
		return nil
	}
	opts := []orchestrator.Option{}
	if deps.ledgerClient != nil {
		opts = append(opts, orchestrator.WithLedgerClient(deps.ledgerClient))
	}

	if deps.gatewayInvokeResolver != nil {
		opts = append(opts, orchestrator.WithGatewayInvokeResolver(deps.gatewayInvokeResolver))
	}
	if routes := buildCardGatewayRoutes(cfg.CardGateways); len(routes) > 0 {
		opts = append(opts, orchestrator.WithCardGatewayRoutes(routes))
	}
	opts = append(opts, orchestrator.WithBatchOptimizationPolicy(buildBatchOptimizationPolicy(cfg.Optimizer)))
	if registry := buildGatewayRegistry(i.logger, cfg.GatewayInstances, i.discoveryReg); registry != nil {
		opts = append(opts, orchestrator.WithGatewayRegistry(registry))
	}
	return opts
}
