package serverimp

import (
	"github.com/tech/sendico/payments/orchestrator/internal/appversion"
	"github.com/tech/sendico/pkg/discovery"
	msg "github.com/tech/sendico/pkg/messaging"
	msgproducer "github.com/tech/sendico/pkg/messaging/producer"
	"github.com/tech/sendico/pkg/mservice"
	"go.uber.org/zap"
)

func (i *Imp) initDiscovery(cfg *config) {
	if cfg == nil || cfg.Messaging == nil || cfg.Messaging.Driver == "" {
		return
	}
	logger := i.logger.Named("discovery")
	broker, err := msg.CreateMessagingBroker(logger.Named("bus"), cfg.Messaging)
	if err != nil {
		i.logger.Warn("Failed to initialise discovery broker", zap.Error(err))
		return
	}
	producer := msgproducer.NewProducer(logger.Named("producer"), broker)
	registry := discovery.NewRegistry()
	watcher, err := discovery.NewRegistryWatcher(i.logger, broker, registry)
	if err != nil {
		i.logger.Warn("Failed to initialise discovery registry watcher", zap.Error(err))
	} else if err := watcher.Start(); err != nil {
		i.logger.Warn("Failed to start discovery registry watcher", zap.Error(err))
	} else {
		i.discoveryWatcher = watcher
		i.discoveryReg = registry
		i.logger.Info("Discovery registry watcher started")
	}
	announce := discovery.Announcement{
		Service:    mservice.PaymentOrchestrator,
		Operations: []string{discovery.OperationPaymentInitiate},
		InvokeURI:  cfg.GRPC.DiscoveryInvokeURI(),
		Version:    appversion.Create().Short(),
	}
	i.discoveryAnnouncer = discovery.NewAnnouncer(i.logger, producer, mservice.PaymentOrchestrator, announce)
	i.discoveryAnnouncer.Start()
}

func (i *Imp) stopDiscovery() {
	if i.discoveryAnnouncer != nil {
		i.discoveryAnnouncer.Stop()
	}
	if i.discoveryWatcher != nil {
		i.discoveryWatcher.Stop()
	}
}
