package serverimp

import (
	"context"

	"github.com/tech/sendico/payments/methods/internal/service/methods"
	"github.com/tech/sendico/payments/storage"
	mongostorage "github.com/tech/sendico/payments/storage/mongo"
	"github.com/tech/sendico/pkg/db"
	"github.com/tech/sendico/pkg/merrors"
	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/mservice"
	"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()
	if i.dbFactory != nil {
		i.dbFactory.CloseConnection()
		i.dbFactory = nil
	}
}

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

	i.initDiscovery(cfg)

	if cfg.Database == nil {
		return merrors.InvalidArgument("database configuration is required")
	}

	permissionsDB := cfg.PermissionsDatabase
	if permissionsDB == nil {
		i.logger.Info("Permissions_database is not configured, falling back to database settings")
		permissionsDB = cfg.Database
	}

	i.dbFactory, err = db.NewConnection(i.logger, permissionsDB)
	if err != nil {
		return err
	}

	policy, err := i.dbFactory.Permissions().GetPolicyDescription(context.Background(), mservice.PaymentMethods)
	if err != nil {
		i.dbFactory.CloseConnection()
		i.dbFactory = nil
		return err
	}

	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 recipient notifications broker", zap.Error(err))
		}
	}

	repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
		return mongostorage.New(
			logger,
			conn,
			mongostorage.WithPaymentMethodsAuth(i.dbFactory.Permissions().Enforcer(), policy.ID),
		)
	}

	serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
		opts := []methods.Option{}
		if broker != nil {
			opts = append(opts, methods.WithRecipientEventsBroker(broker))
		}

		i.startDiscoveryAnnouncer(cfg, producer)
		svc, err := methods.NewService(logger, repo, opts...)
		if err != nil {
			return nil, err
		}
		i.service = svc
		return svc, nil
	}

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

	if err := i.app.Start(); err != nil {
		if i.dbFactory != nil {
			i.dbFactory.CloseConnection()
			i.dbFactory = nil
		}
		return err
	}
	return nil
}
