package middleware

import (
	"eslogad-be/internal/constants"
	"eslogad-be/internal/logger"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func HTTPStatLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.URL.Path == "/health" {
			c.Next()
			return
		}

		start := time.Now()
		c.Next()
		duration := time.Since(start)

		status := c.Writer.Status()

		log := logger.NewContextLogger(c, "HTTPStatLogger")
		log.Infof("CompletedHTTPRequest %v", map[string]string{
			constants.RequestMethod:        c.Request.Method,
			constants.RequestPath:          c.Request.URL.Path,
			constants.RequestURLQueryParam: c.Request.URL.RawQuery,
			constants.ResponseStatusCode:   fmt.Sprintf("%d", status),
			constants.ResponseStatusText:   http.StatusText(status),
			constants.ResponseTimeTaken:    fmt.Sprintf("%f", duration.Seconds()),
		})
	}
}
