package server

import (
	"context"
	"net"

	"github.com/prometheus/client_golang/prometheus"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/observability"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/nettool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/tlstool"
)

type Factory struct {
	Gatherer   prometheus.Gatherer
	Registerer prometheus.Registerer
}

func (f *Factory) New(config *modserver.Config) (modserver.Module, error) {
	listenCfg := config.Config.Observability.Listen
	var listener func(context.Context) (net.Listener, error)

	tlsConfig, err := tlstool.MaybeServerConfig(listenCfg.GetCertificateFile(), listenCfg.GetKeyFile())
	if err != nil {
		return nil, err
	}
	if tlsConfig != nil {
		listener = func(ctx context.Context) (net.Listener, error) {
			return nettool.TLSListenWithOSTCPKeepAlive(ctx, *listenCfg.Network, listenCfg.Address, tlsConfig)
		}
	} else {
		listener = func(ctx context.Context) (net.Listener, error) {
			return nettool.ListenWithOSTCPKeepAlive(ctx, *listenCfg.Network, listenCfg.Address)
		}
	}
	return &module{
		log:           config.Log,
		api:           config.API,
		cfg:           config.Config.Observability,
		listener:      listener,
		gatherer:      f.Gatherer,
		registerer:    f.Registerer,
		serverName:    config.KASNameVersion,
		probeRegistry: config.ProbeRegistry,
	}, nil
}

func (f *Factory) Name() string {
	return observability.ModuleName
}
