/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package router

func NewLoggingMiddleware(print func(string, ...any)) MiddlewareFunc {
	mw := func(next Handler) Handler {
		return newLoggingHandler(next, print)
	}
	return mw
}

type loggingHandler struct {
	next      Handler
	printFunc func(string, ...any)
}

func newLoggingHandler(next Handler, print func(string, ...any)) *loggingHandler {
	return &loggingHandler{
		next:      next,
		printFunc: print,
	}
}

func (logging loggingHandler) ServeHTTP(rctx *Context) {
	logging.next.ServeHTTP(rctx)
	cl := rctx.Writer.Header().Get("Content-Length")
	logging.printFunc("%s %s %s %s %s %d", rctx.Request.RemoteAddr,
		rctx.Request.Method, rctx.Request.URL.String(),
		rctx.Request.Proto, cl, rctx.StatusCode)
}
