package middlewares

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/AlchemyTelcoSolutions/callisto-so-bff/cmd/app/config"
	"github.com/AlchemyTelcoSolutions/xutils-go/xlogger"
	"go.uber.org/zap"
)

// AllowedPaths is a handler function to filter paths with a given []string config
func AllowedPaths(logger xlogger.Logger, c config.Proxy) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			if len(c.Paths) < 1 || !c.IsEnabled {
				next.ServeHTTP(w, r)
				return
			}

			for path := range c.Paths {
				if strings.HasPrefix(r.URL.Path, path) {
					next.ServeHTTP(w, r)
					return
				}
			}
			logger.Info(
				fmt.Sprintf("return 404 on path requested as this is not allowed, path: %s", r.URL.Path),
				zap.String("ctx2", "invalid path"),
			)
			// returning the default error message
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		}
		return http.HandlerFunc(fn)
	}
}
