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
	}

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

	// Initialize the Continuous Profiler.
	profOpts := profilerOpts{ServiceVersion: config.version}
	initProfiler(profOpts)

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

	serveMux := http.NewServeMux()
	serveMux.Handle("/metrics", promhttp.Handler())

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

	return http.Serve(listener, serveMux)
}

// 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...)
}
