package middleware

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

	"github.com/stretchr/testify/require"
)

func TestRequestID_GeneratesWhenAbsent(t *testing.T) {
	var seen string
	h := RequestID(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
		seen = RequestIDFromContext(r.Context())
	}))

	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
	require.NotEmpty(t, seen)
	require.Equal(t, seen, rec.Header().Get("X-Request-ID"))
}

func TestRequestID_PreservesClientHeader(t *testing.T) {
	const given = "client-supplied-id"
	var seen string
	h := RequestID(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
		seen = RequestIDFromContext(r.Context())
	}))

	req := httptest.NewRequest("GET", "/", nil)
	req.Header.Set("X-Client-Request-ID", given)

	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	require.Equal(t, given, seen)
	require.Equal(t, given, rec.Header().Get("X-Request-ID"))
}
