package serverimp

import (
	"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
	"github.com/tech/sendico/payments/storage"
	mongostorage "github.com/tech/sendico/payments/storage/mongo"
	"github.com/tech/sendico/pkg/db"
	msg "github.com/tech/sendico/pkg/messaging"
	mb "github.com/tech/sendico/pkg/messaging/broker"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/server/grpcapp"
	"go.uber.org/zap"
)

func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
	return &Imp{
		logger: logger.Named("server"),
		file:   file,
		debug:  debug,
	}, nil
}

func (i *Imp) Shutdown() {
	i.stopDiscovery()
	if i.service != nil {
		i.service.Shutdown()
	}
	i.shutdownApp()
	i.closeClients()
}

func (i *Imp) Start() error {
	cfg, err := i.loadConfig()
	if err != nil {
		return err
	}
	i.config = cfg

	i.initDiscovery(cfg)

	quoteRetention := cfg.quoteRetention()
	repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
		return mongostorage.New(logger, conn, mongostorage.WithQuoteRetention(quoteRetention))
	}

	var broker mb.Broker
	if cfg.Messaging != nil && cfg.Messaging.Driver != "" {
		broker, err = msg.CreateMessagingBroker(i.logger, cfg.Messaging)
		if err != nil {
			i.logger.Warn("Failed to create messaging broker", zap.Error(err))
		}
	}

	deps := i.initDependencies(cfg)

	serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
		opts := i.buildServiceOptions(cfg, deps)
		if broker != nil {
			opts = append(opts, orchestrator.WithPaymentGatewayBroker(broker))
		}
		svc, err := orchestrator.NewService(logger, repo, producer, opts...)
		i.service = svc
		return svc, err
	}

	app, err := grpcapp.NewApp(i.logger, "payments.orchestrator", cfg.Config, i.debug, repoFactory, serviceFactory)
	if err != nil {
		return err
	}
	i.app = app

	return i.app.Start()
}
