package monitoring_test

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

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"github.com/user-management-system/internal/monitoring"
)

func TestPrometheusHandlerForRegistryExposesBusinessMetrics(t *testing.T) {
	gin.SetMode(gin.TestMode)

	metrics := monitoring.NewMetrics()
	router := gin.New()
	router.Use(monitoring.PrometheusMiddleware(metrics))
	router.GET("/ready", func(c *gin.Context) {
		c.Status(http.StatusNoContent)
	})
	router.GET("/metrics", gin.WrapH(promhttp.HandlerFor(metrics.GetRegistry(), promhttp.HandlerOpts{})))

	recorder := httptest.NewRecorder()
	request := httptest.NewRequest(http.MethodGet, "/ready", nil)
	router.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusNoContent {
		t.Fatalf("expected 204, got %d", recorder.Code)
	}

	metricsRecorder := httptest.NewRecorder()
	metricsRequest := httptest.NewRequest(http.MethodGet, "/metrics", nil)
	router.ServeHTTP(metricsRecorder, metricsRequest)
	if metricsRecorder.Code != http.StatusOK {
		t.Fatalf("expected metrics endpoint to return 200, got %d", metricsRecorder.Code)
	}

	body := metricsRecorder.Body.String()
	if !strings.Contains(body, `http_requests_total{method="GET",path="/ready",status="204"} 1`) {
		t.Fatalf("expected recorded request metric in body, got %s", body)
	}
	if !strings.Contains(body, `http_request_duration_seconds_bucket{method="GET",path="/ready"`) {
		t.Fatalf("expected recorded request duration metric in body, got %s", body)
	}
}
