package middlewares

import (
	"net/http"

	"github.com/AlchemyTelcoSolutions/xutils-go/xlogger"
	"github.com/go-chi/chi/v5"
)

type ProxyNotFoundPathInterface interface {
	ForwarRequest(http.ResponseWriter, *http.Request, string)
}

func ProxyNotFoundPaths(logger xlogger.Logger, s ProxyNotFoundPathInterface) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			// Temporary routing context used to match Method and path
			tctx := chi.NewRouteContext()

			// get the chi route context
			rctx := chi.RouteContext(r.Context())

			// if route doesn't match forward the request
			if !rctx.Routes.Match(tctx, r.Method, r.URL.Path) {
				s.ForwarRequest(w, r, r.URL.Path)
				return
			}
			next.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)
	}
}
