package middleware

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

	"github.com/gin-gonic/gin"
)

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

	r := gin.New()
	r.Use(RequestID())
	r.GET("/x", func(c *gin.Context) {
		c.String(200, c.GetHeader("X-Request-ID"))
	})

	req := httptest.NewRequest(http.MethodGet, "/x", nil)
	rr := httptest.NewRecorder()
	r.ServeHTTP(rr, req)

	if rr.Code != 200 {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	id := rr.Header().Get("X-Request-ID")
	if id == "" {
		t.Fatalf("expected X-Request-ID response header")
	}
	if rr.Body.String() != id {
		t.Fatalf("expected body to echo X-Request-ID, got %q want %q", rr.Body.String(), id)
	}
}

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

	r := gin.New()
	r.Use(RequestID())
	r.GET("/x", func(c *gin.Context) {
		c.String(200, c.GetHeader("X-Request-ID"))
	})

	req := httptest.NewRequest(http.MethodGet, "/x", nil)
	req.Header.Set("X-Request-ID", "req-abc")
	rr := httptest.NewRecorder()
	r.ServeHTTP(rr, req)

	if rr.Code != 200 {
		t.Fatalf("expected 200, got %d", rr.Code)
	}
	if got := rr.Header().Get("X-Request-ID"); got != "req-abc" {
		t.Fatalf("expected preserved X-Request-ID, got %q", got)
	}
}

