package middleware

import (
	"context"
	"heruvym/jwt_adapter"
	"net/http"
)

func (mw *Middleware) MiddlewareGetJwt(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Escape non-GET requests
		if r.Method != http.MethodGet {
			next.ServeHTTP(w, r)
			return
		}
		ctx := r.Context()

		bearer := r.URL.Query().Get(jwt_adapter.DefaultHeaderKey)
		if bearer != "" {

			adapter, err := jwt_adapter.Decode(bearer)
			if err == nil {
				//mw.logger.Emit(ErrorJwtAccess{Err: err})
				//w.WriteHeader(http.StatusUnauthorized)
				//return
				ctx = context.WithValue(r.Context(), jwt_adapter.DefaultHeaderKey, adapter)
				//
			}
		} else {
			sess := r.URL.Query().Get("s")
			if sess == "" {
				return
			}
			ctx = context.WithValue(r.Context(), jwt_adapter.DefaultHeaderKey, &jwt_adapter.JwtAdapter{Id: sess})
		}

		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
