package monitoring

import (
	"log"
	"net/http"
	"net/http/pprof"

	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Start will start a new monitoring service listening on the address
// configured through the option arguments. Additionally, it'll start
// a Continuous Profiler configured through environment variables
// (see more at https://gitlab.com/gitlab-org/labkit/-/blob/master/monitoring/doc.go).
//
// If `WithListenerAddress` option is provided, Start will block or return a non-nil error,
// similar to `http.ListenAndServe` (for instance).
func Start(options ...Option) error {
	config := applyOptions(options)
	listener, err := config.listenerFactory()
	if err != nil {
		return err
	}

	// Initialize the Continuous Profiler.
	if !config.continuousProfilingDisabled {
		profOpts := profilerOpts{
			ServiceVersion:  config.version,
			CredentialsFile: config.profilerCredentialsFile,
		}
		initProfiler(profOpts)
	}

	if listener == nil {
		// No listener has been configured, skip mux setup.
		return nil
	}

	metricsHandler(config)
	pprofHandlers(config)

	return http.Serve(listener, config.serveMux)
}

func metricsHandler(cfg optionsConfig) {
	if cfg.metricsDisabled {
		return
	}

	// Register the `gitlab_build_info` metric if configured
	if len(cfg.buildInfoGaugeLabels) > 0 {
		registerBuildInfoGauge(cfg.registerer, cfg.buildInfoGaugeLabels)
	}

	cfg.serveMux.Handle(
		cfg.metricsHandlerPattern,
		promhttp.InstrumentMetricHandler(cfg.registerer, promhttp.HandlerFor(cfg.gatherer, promhttp.HandlerOpts{})),
	)
}

func pprofHandlers(cfg optionsConfig) {
	if cfg.pprofDisabled {
		return
	}

	cfg.serveMux.HandleFunc("/debug/pprof/", pprof.Index)
	cfg.serveMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	cfg.serveMux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	cfg.serveMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	cfg.serveMux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}

// Serve will start a new monitoring service listening on the address
// configured through the option arguments. Additionally, it'll start
// a Continuous Profiler configured through environment variables
// (see more at https://gitlab.com/gitlab-org/labkit/-/blob/master/monitoring/doc.go).
//
// If `WithListenerAddress` option is provided, Serve will block or return a non-nil error,
// similar to `http.ListenAndServe` (for instance).
//
// Deprecated: Use Start instead.
func Serve(options ...Option) error {
	log.Print("warning: deprecated function, use Start instead")

	return Start(options...)
}
