package server

import (
	"context"
	"log/slog"
	"net"

	"github.com/prometheus/client_golang/prometheus"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/observability"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/logz"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/pkg/kascfg"
)

type module struct {
	log           *slog.Logger
	api           modshared.API
	cfg           *kascfg.ObservabilityCF
	listener      func(context.Context) (net.Listener, error)
	gatherer      prometheus.Gatherer
	registerer    prometheus.Registerer
	serverName    string
	probeRegistry *observability.ProbeRegistry
}

func (m *module) Run(ctx context.Context) (retErr error) {
	lis, err := m.listener(ctx)
	if err != nil {
		return err
	}
	// Error is ignored because metricSrv.Run() closes the listener and
	// a second close always produces an error.
	defer lis.Close() //nolint:errcheck

	m.log.Info("Observability endpoint is up",
		logz.NetNetworkFromAddr(lis.Addr()),
		logz.NetAddressFromAddr(lis.Addr()),
	)

	metricSrv := observability.MetricServer{
		Log:                   m.log,
		API:                   m.api,
		Name:                  m.serverName,
		Listener:              lis,
		PrometheusURLPath:     m.cfg.Prometheus.UrlPath,
		LivenessProbeURLPath:  m.cfg.LivenessProbe.UrlPath,
		ReadinessProbeURLPath: m.cfg.ReadinessProbe.UrlPath,
		Gatherer:              m.gatherer,
		Registerer:            m.registerer,
		ProbeRegistry:         m.probeRegistry,
	}
	return metricSrv.Run(ctx)
}

func (m *module) Name() string {
	return observability.ModuleName
}
