package infra

import (
	"net/http"
	"time"
)

// LoggerMiddleware retorna un Middleware que emite un log estructurado por cada request HTTP.
// Cada request produce una entrada a nivel info con method, path, status y duration_ms.
// Respeta los campos contextuales que ya tenga el logger (app, version, request_id...).
func LoggerMiddleware(logger *Logger) Middleware {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			rw := &loggerResponseWriter{ResponseWriter: w, status: http.StatusOK}
			next.ServeHTTP(rw, r)
			duration := time.Since(start)
			LogInfo(logger, "http request",
				"method", r.Method,
				"path", r.URL.Path,
				"status", rw.status,
				"duration_ms", duration.Milliseconds(),
			)
		})
	}
}

// loggerResponseWriter captura el status code escrito al ResponseWriter.
// Nombrado distinto de responseWriter (http_logger_middleware.go) para evitar colision.
type loggerResponseWriter struct {
	http.ResponseWriter
	status int
}

func (rw *loggerResponseWriter) WriteHeader(status int) {
	rw.status = status
	rw.ResponseWriter.WriteHeader(status)
}
