package routers

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/metrics"
	"github.com/tech/sendico/pkg/mlogger"
	"go.uber.org/zap"
)

type metricsRouter struct {
	logger  mlogger.Logger
	handler http.Handler
}

func (mr *metricsRouter) Finish() {
	mr.logger.Debug("Stopped")
}

func (mr *metricsRouter) handle(w http.ResponseWriter, r *http.Request) {
	mr.logger.Debug("Serving metrics request...")
	mr.handler.ServeHTTP(w, r)
}

func newMetricsRouter(logger mlogger.Logger, router chi.Router, endpoint string) *metricsRouter {
	mr := metricsRouter{
		logger:  logger.Named("metrics"),
		handler: metrics.Handler(),
	}

	logger.Debug("Installing Prometheus middleware...")
	router.Group(func(r chi.Router) {
		ep := endpoint + "/metrics"
		r.Get(ep, mr.handle)
		logger.Info("Prometheus handler installed", zap.String("endpoint", ep))
	})

	return &mr
}
