package runtime

import (
	"context"
	"net/http"

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

type Exporter interface {
	Name() string
	Register(ctx context.Context, reg prometheus.Registerer)
}

type Config struct {
	MetricsPath string
	HealthPath  string
}

type Server struct {
	handler http.Handler
}

func NewServer(cfg Config, exporters []Exporter) *Server {
	mux := http.NewServeMux()

	mux.Handle(cfg.MetricsPath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		reg := prometheus.NewRegistry()
		for _, exporter := range exporters {
			exporter.Register(r.Context(), reg)
		}
		promhttp.HandlerFor(reg, promhttp.HandlerOpts{}).ServeHTTP(w, r)
	}))
	mux.HandleFunc(cfg.HealthPath, func(w http.ResponseWriter, _ *http.Request) {
		_, _ = w.Write([]byte("ok\n"))
	})

	return &Server{handler: mux}
}

func (s *Server) Handler() http.Handler {
	return s.handler
}
