package middleware

import (
	"github.com/UpmeshLTD/urus-aio/infrastructure/logging"
	"time"

	"github.com/gin-gonic/gin"
	"go.opencensus.io/trace"
)

// RequestLogging is a middleware that logs HTTP requests.
func RequestLogging(logger logging.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		now := time.Now()
		c.Next()
		elapsedMs := time.Since(now).Milliseconds()

		span := trace.FromContext(c.Request.Context())
		spanCtx := span.SpanContext()

		logger.Infow(c.Request.URL.Path,
			"timestamp", now,
			"latency_ms", elapsedMs,
			"method", c.Request.Method,
			"status", c.Writer.Status(),
			"client_ip", c.ClientIP(),
			"headers", c.Request.Header,
			"span_id", spanCtx.SpanID.String(),
			"trace_id", spanCtx.TraceID.String(),
		)
	}
}
