package middleware

import (
	"time"

	"counter/internal/infrastructure/config"
	"counter/internal/infrastructure/logging"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// LoggingMiddleware creates a Gin middleware for HTTP request logging
func LoggingMiddleware(logger logging.Logger, cfg *config.Config) gin.HandlerFunc {
	return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// Create structured log entry with default fields
		entry := logger.WithFields(logrus.Fields{
			"service":     "counter-app",
			"environment": string(cfg.Environment),
			"version":     "1.0.0",
			"method":      param.Method,
			"path":        param.Path,
			"status":      param.StatusCode,
			"latency":     param.Latency.String(),
			"client_ip":   param.ClientIP,
			"user_agent":  param.Request.UserAgent(),
			"timestamp":   param.TimeStamp.Format(time.RFC3339),
		})

		// Set log level based on status code
		switch {
		case param.StatusCode >= 500:
			entry.Error("HTTP Request")
		case param.StatusCode >= 400:
			entry.Warn("HTTP Request")
		default:
			entry.Info("HTTP Request")
		}

		// Return empty string since we're handling logging ourselves
		return ""
	})
}
