package middleware

import (
	"net/http"

	"github.com/google/uuid"
)

const headerRequestID = "X-Request-Id"

// RequestID is a middleware that attaches a UUID v7 to every request.
// If the incoming request already carries an X-Request-Id header the value is
// reused; otherwise a new UUID v7 is generated.
// The ID is injected into the request context (accessible via RequestIDFromContext)
// and echoed back in the X-Request-Id response header.
func RequestID(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get(headerRequestID)
		if id == "" {
			id = uuid.Must(uuid.NewV7()).String()
		}

		ctx := withRequestID(r.Context(), id)
		w.Header().Set(headerRequestID, id)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
