package middleware

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

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/testutil"
)

func newEngine() *gin.Engine {
	gin.SetMode(gin.TestMode)
	r := gin.New()
	r.Use(RequestID(), Observe())
	r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })
	return r
}

func TestObserve_CountsAndRequestID(t *testing.T) {
	r := newEngine()
	before := testutil.ToFloat64(httpRequests.WithLabelValues("GET", "/ping", "200"))

	w := httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/ping", nil))

	if w.Code != 200 {
		t.Fatalf("状态码=%d", w.Code)
	}
	if w.Header().Get("X-Request-ID") == "" {
		t.Error("应自动生成并回写 X-Request-ID")
	}
	after := testutil.ToFloat64(httpRequests.WithLabelValues("GET", "/ping", "200"))
	if after != before+1 {
		t.Errorf("请求计数应 +1：before=%v after=%v", before, after)
	}
}

func TestRequestID_PropagatesIncoming(t *testing.T) {
	r := newEngine()
	w := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/ping", nil)
	req.Header.Set("X-Request-ID", "trace-abc-123")
	r.ServeHTTP(w, req)
	if got := w.Header().Get("X-Request-ID"); got != "trace-abc-123" {
		t.Errorf("应透传入站 X-Request-ID，got %q", got)
	}
}
