package serverimp

import (
	"context"
	"os"
	"time"

	"github.com/tech/sendico/fx/oracle/internal/service/oracle"
	"github.com/tech/sendico/fx/storage"
	mongostorage "github.com/tech/sendico/fx/storage/mongo"
	"github.com/tech/sendico/pkg/api/routers"
	"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"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
)

type Imp struct {
	logger mlogger.Logger
	file   string
	debug  bool

	config  *config
	app     *grpcapp.App[storage.Repository]
	service *oracle.Service
}

type config struct {
	*grpcapp.Config `yaml:",inline"`
	MaxQuoteTTLMs   int64 `yaml:"max_quote_ttl_ms"`
}

const (
	defaultMaxQuoteTTL       = 10 * time.Minute
	defaultMaxQuoteTTLMillis = int64(defaultMaxQuoteTTL / time.Millisecond)
)

func (c *config) maxQuoteTTLMillis() int64 {
	if c == nil || c.MaxQuoteTTLMs <= 0 {
		return defaultMaxQuoteTTLMillis
	}
	return c.MaxQuoteTTLMs
}

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() {
	if i.app == nil {
		return
	}
	if i.service != nil {
		i.service.Shutdown()
	}
	timeout := 15 * time.Second
	if i.config != nil && i.config.Runtime != nil {
		timeout = i.config.Runtime.ShutdownTimeout()
	}
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	i.app.Shutdown(ctx)
	cancel()
}

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

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

	serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
		svc := oracle.NewService(
			logger,
			repo,
			producer,
			cfg.GRPC.DiscoveryInvokeURI(),
			oracle.WithMaxQuoteTTLMillis(cfg.maxQuoteTTLMillis()),
		)
		i.service = svc
		return svc, nil
	}

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

	return i.app.Start()
}

func (i *Imp) loadConfig() (*config, error) {
	data, err := os.ReadFile(i.file)
	if err != nil {
		i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
		return nil, err
	}

	cfg := &config{Config: &grpcapp.Config{}}
	if err := yaml.Unmarshal(data, cfg); err != nil {
		i.logger.Error("Failed to parse configuration", zap.Error(err))
		return nil, err
	}

	if cfg.Runtime == nil {
		cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
	}

	if cfg.GRPC == nil {
		cfg.GRPC = &routers.GRPCConfig{
			Network:          "tcp",
			Address:          ":50051",
			EnableReflection: true,
			EnableHealth:     true,
		}
	}

	return cfg, nil
}
