package api

import (
	"net/http"
	"strings"

	"github.com/labstack/echo/v4"
)

func tokenMiddlware(configuredToken string) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// Ignore token check for swagger URLs
			if strings.HasPrefix(c.Request().URL.Path, "/swagger") || c.Request().URL.Path == "/" {
				return next(c)
			}

			// Check for token in the Authorization header
			authHeader := c.Request().Header.Get("Authorization")
			if authHeader == "" {
				return echo.NewHTTPError(http.StatusUnauthorized, "please provide valid token")
			}

			// The Authorization header should be in the format "Bearer <token>"
			parts := strings.Split(authHeader, " ")
			if len(parts) == 1 && parts[0] == configuredToken {
				return next(c)
			}

			if len(parts) != 2 || parts[0] != "Bearer" {
				return echo.NewHTTPError(http.StatusUnauthorized, "please provide valid token")
			}

			if parts[1] != configuredToken {
				return echo.NewHTTPError(http.StatusUnauthorized, "please provide valid token")
			}

			return next(c)
		}
	}
}