package server

import (
	"fmt"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5/middleware"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)

func (s *Server) MiddlewareLogging(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

		reqID := middleware.GetReqID(r.Context())

		t1 := time.Now()
		defer func() {
			s.Logger.Info("Served request.",
				"status", ww.Status(),
				"method", r.Method,
				"path", r.URL.Path,
				"duration", time.Since(t1),
				"remote", r.RemoteAddr,
				"written", ww.BytesWritten(),
				"req", reqID,
			)
			s.Logger.Debug("Debug info.",
				"req", reqID,
				"headers", r.Header,
			)
		}()
		next.ServeHTTP(ww, r)
	}
	return http.HandlerFunc(fn)
}

func (s *Server) MiddlewareTracing(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		h := otelhttp.NewHandler(next, fmt.Sprintf("%s %s", r.Method, r.URL.Path))

		h.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}