package api

import (
	"net/http"
	"producer/internal/logging"
	"time"
)

// Middleware para logging de solicitudes HTTP
func requestLoggerMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		// Crear un responseWriter personalizado para capturar el status code
		rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}

		// Llamar al siguiente handler
		next.ServeHTTP(rw, r)

		// Logging después de procesar
		duration := time.Since(start)
		logging.InfoLogger.Printf(
			"%s %s %d %s - %s",
			r.Method,
			r.RequestURI,
			rw.statusCode,
			duration,
			r.UserAgent(),
		)
	})
}

// responseWriter personalizado para capturar el status code
type responseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (rw *responseWriter) WriteHeader(code int) {
	rw.statusCode = code
	rw.ResponseWriter.WriteHeader(code)
}
