package serverconfig

import (
	"strings"

	"bitbucket.org/nemt/nemt-portal-api/server/router/routeutils"
	"github.com/labstack/echo"
)

// authSkipper is the default skipper for authentication and authorization
func authSkipper(ctx echo.Context) bool {
	path := ctx.Request().URL.Path
	return (strings.HasPrefix(path, "/health") ||
		strings.HasPrefix(path, "/v1/authenticate") ||
		strings.HasPrefix(path, "/v1/docs") ||
		strings.HasPrefix(path, "/v1/twilio") ||
		strings.HasPrefix(path, "/v1/twilio/ws") ||
		strings.Contains(path, "/v1/ext") ||
		strings.Contains(path, "/v1/notification/ws") ||
		strings.HasPrefix(path, "/v1/lyfthook") ||
		strings.HasPrefix(path, "/v1/docs") ||
		strings.HasPrefix(path, "/v1/selfregister") ||
		strings.HasPrefix(path, "/v1/passwordreset"))
}

// appSkipper is the default skipper for the application routes
func appSkipper(ctx echo.Context) bool {
	path := ctx.Request().URL.Path
	return strings.HasPrefix(path, "/v1/twilio")
}

// docsSkipper is the default skipper for documentation
func docsSkipper(ctx echo.Context) bool {
	path := ctx.Request().URL.Path
	return strings.HasPrefix(path, "/v1/docs")
}

// middlewareErrorWrapper wraps a middleware and applies the default error handling to response
func middlewareErrorWrapper(middleware echo.MiddlewareFunc) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		handlerFunc := middleware(next)

		return func(c echo.Context) error {
			err := handlerFunc(c)
			if err != nil {
				return routeutils.HandleAPIError(c, err)
			}

			return nil
		}
	}
}
