package middleware

import (
	"context"
	"eslogad-be/internal/appcontext"
	"eslogad-be/internal/constants"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func CorrelationID() gin.HandlerFunc {
	return func(c *gin.Context) {
		correlationID := c.GetHeader(constants.CorrelationIDHeader)
		if correlationID == "" {
			correlationID = uuid.New().String()
		}
		ctx := context.WithValue(c.Request.Context(), appcontext.CorrelationIDKey, correlationID)
		c.Request = c.Request.WithContext(ctx)
		c.Writer.Header().Set(constants.CorrelationIDHeader, correlationID)
		c.Next()
	}
}
