package metrics

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/prometheus/client_golang/prometheus/testutil"
	"github.com/stretchr/testify/require"
)

func TestInstrumentHandlerRecordsRequest(t *testing.T) {
	const route = "/test/instrumented"
	HTTPRequestsTotal.DeleteLabelValues(route, http.MethodPost, "418")
	HTTPRequestDuration.DeleteLabelValues(route, http.MethodPost)
	t.Cleanup(func() {
		HTTPRequestsTotal.DeleteLabelValues(route, http.MethodPost, "418")
		HTTPRequestDuration.DeleteLabelValues(route, http.MethodPost)
	})

	handler := InstrumentHandler(route, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		http.Error(w, "teapot", http.StatusTeapot)
	}))
	request := httptest.NewRequest(http.MethodPost, route, nil)
	response := httptest.NewRecorder()

	handler.ServeHTTP(response, request)

	require.Equal(t, http.StatusTeapot, response.Code)
	require.Equal(t, float64(1),
		testutil.ToFloat64(HTTPRequestsTotal.WithLabelValues(route, http.MethodPost, "418")))
}

func TestInstrumentHandlerNormalizesUnknownMethod(t *testing.T) {
	const route = "/test/unknown-method"
	HTTPRequestsTotal.DeleteLabelValues(route, "OTHER", "204")
	t.Cleanup(func() {
		HTTPRequestsTotal.DeleteLabelValues(route, "OTHER", "204")
		HTTPRequestDuration.DeleteLabelValues(route, "OTHER")
	})

	handler := InstrumentHandler(route, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	}))
	request := httptest.NewRequest("CUSTOM-METHOD", route, nil)
	response := httptest.NewRecorder()

	handler.ServeHTTP(response, request)

	require.Equal(t, float64(1),
		testutil.ToFloat64(HTTPRequestsTotal.WithLabelValues(route, "OTHER", "204")))
}
