package serverimp

import (
	quotesvc "github.com/tech/sendico/payments/quotation/internal/service/quotation"
	"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"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/server/grpcapp"
)

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.closeDependencies()
}

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

	i.initDiscovery(cfg)
	i.deps = i.initDependencies(cfg)

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

	serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
		opts := []quotesvc.Option{}
		if i.deps != nil {
			if i.deps.feesClient != nil {
				opts = append(opts, quotesvc.WithFeeEngine(i.deps.feesClient, cfg.Fees.callTimeout()))
			}
			if i.deps.oracleClient != nil {
				opts = append(opts, quotesvc.WithOracleClient(i.deps.oracleClient))
			}
			if i.deps.ledgerClient != nil {
				opts = append(opts, quotesvc.WithLedgerClient(i.deps.ledgerClient))
			}
			if i.deps.gatewayResolver != nil {
				opts = append(opts, quotesvc.WithChainGatewayResolver(i.deps.gatewayResolver))
			}
			if i.deps.gatewayInvokeResolver != nil {
				opts = append(opts, quotesvc.WithGatewayInvokeResolver(i.deps.gatewayInvokeResolver))
			}
		}
		if registry := quotesvc.NewDiscoveryGatewayRegistry(logger, i.discoveryReg); registry != nil {
			opts = append(opts, quotesvc.WithGatewayRegistry(registry))
		}
		i.startDiscoveryAnnouncer(cfg, producer)
		svc := quotesvc.NewQuotationService(logger, repo, opts...)
		i.service = svc
		return svc, nil
	}

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

	return i.app.Start()
}
