package middleware

import (
	"encoding/json"
	"log"
	"os"
	"time"

	"github.com/acp/interceptor/internal/tracing"
	"github.com/gin-gonic/gin"
)

// StructuredLogging emits one JSON line per request with latency and status.
func StructuredLogging() gin.HandlerFunc {
	logger := log.New(os.Stdout, "", 0)
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()

		line := map[string]any{
			"msg":          "http_request",
			"method":       c.Request.Method,
			"path":         c.FullPath(),
			"raw_path":     c.Request.URL.Path,
			"status":       c.Writer.Status(),
			"latency_ms":   time.Since(start).Milliseconds(),
			"client_ip":    c.ClientIP(),
			"trace_id":     tracing.TraceIDFromContext(c),
			"user_agent":   c.Request.UserAgent(),
			"request_size": c.Request.ContentLength,
		}
		b, _ := json.Marshal(line)
		logger.Println(string(b))
	}
}
