package monitoring

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

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

// Serve will start a new monitoring service listening on the address
// configured through the option arguments.
//
// Serve is blocking and always returns a non-nil error, similar to
// `http.ListenAndServe` (for instance).
func Serve(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)
	}

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