package middlewarex

import (
	"net/http"
	"time"

	"github.com/go-chi/chi/v5/middleware"
	"golang.org/x/exp/slog"
)

func SlogRequestLogger(logger *slog.Logger) func(next http.Handler) http.Handler {
	if logger == nil {
		return func(next http.Handler) http.Handler { return next }
	}

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
			ti := time.Now()

			defer func() {
				reqLogger := logger.With(
					slog.String("proto", r.Proto),
					slog.String("path", r.URL.Path),
					slog.String("reqId", middleware.GetReqID(r.Context())),
					slog.Duration("lat", time.Since(ti)),
					slog.Int("status", ww.Status()),
					slog.Int("size", ww.BytesWritten()),
				)

				reqLogger.Info("Served")
			}()

			next.ServeHTTP(ww, r)
		})
	}
}
