package controllers

import (
	"log"
	"net/http"
	"time"
)

type Middleware func(http.Handler) http.Handler

var (
	MiddlewaresChain = createMiddlewaresChain(
		loggingMiddleware,
	)
)

/*
Возвращает один middleware, который объединяет все переданные

createMiddlewaresChain(m1, m2, m3)
= func(next http.Handler) http.Handler { return m1(m2(m3(final))) }
*/
func createMiddlewaresChain(middlewares ...Middleware) Middleware {
	return func(final http.Handler) http.Handler {
		for i := len(middlewares) - 1; i >= 0; i-- {
			final = middlewares[i](final)
		}
		return final
	}
}

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		next.ServeHTTP(w, r)

		log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
	})
}
