package auth

import (
	"context"
	"net/http"
)

func Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cookie, err := r.Cookie("access_token")
		if err != nil {
			http.Error(w, "no token", http.StatusUnauthorized)
			return
		}

		claims, err := VerifyToken(cookie.Value)
		if err != nil {
			http.Error(w, "invalid token", http.StatusUnauthorized)
			return
		}

		// Sicherheit: Überprüfe dass es ein access_token ist
		if claims.Type != "access" {
			http.Error(w, "invalid token type", http.StatusUnauthorized)
			return
		}

		ctx := context.WithValue(r.Context(), "user", claims.User)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
