package middleware

import (
	"net/http"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
)

func TraceID(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get(apiresponse.TraceIDHeader)
		if id == "" {
			id = apiresponse.GenerateTraceID()
		}

		w.Header().Set(apiresponse.TraceIDHeader, id)
		ctx := apiresponse.WithTraceID(r.Context(), id)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
