package round_trippers

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

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

type MetricsRoundTripper struct {
	rt http.RoundTripper
}

func NewMetricsRoundTripper(rt http.RoundTripper) http.RoundTripper {
	return &MetricsRoundTripper{
		rt: rt,
	}
}

func (m *MetricsRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
	start := time.Now()
	resp, err := m.rt.RoundTrip(r)

	status := "error"

	if resp != nil {
		status = strconv.Itoa(resp.StatusCode)
	}

	url := r.URL.Path

	metrics.IncOutboundRequestCount(r.Method, url, status)
	metrics.StoreOutboundRequestDuration(r.Method, url, status, time.Since(start))

	return resp, err
}
