package middlewares

import (
	"net/http"
	"strconv"
	"time"

	"route256/cart/internal/infra/http/metrics"
)

type statusWriter struct {
	http.ResponseWriter
	statusCode int
}

func (w *statusWriter) WriteHeader(code int) {
	w.statusCode = code
	w.ResponseWriter.WriteHeader(code)
}

func NewMetricsMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sw := &statusWriter{
			ResponseWriter: w,
			statusCode:     http.StatusOK,
		}

		start := time.Now()

		h.ServeHTTP(sw, r)

		path := r.URL.Path
		status := strconv.Itoa(sw.statusCode)

		metrics.IncRequestHandlerCount(r.Method, path, status)
		metrics.StoreHandlerRequestDuration(r.Method, path, status, time.Since(start))
	})
}
