package auth

import (
	"net/http"
	"strings"
)

// AuthMiddleware extracts and validates JWT tokens from requests
func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			// No token, proceed without user in context
			next.ServeHTTP(w, r)
			return
		}

		// Extract Bearer token
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
			// Invalid header format, proceed without user
			next.ServeHTTP(w, r)
			return
		}

		tokenString := parts[1]
		claims, err := ValidateToken(tokenString)
		if err != nil {
			// Invalid token, proceed without user
			next.ServeHTTP(w, r)
			return
		}

		// Add user to context
		user := &UserContext{
			ID:          claims.UserID,
			Email:       claims.Email,
			Roles:       claims.Roles,
			Permissions: claims.Permissions,
		}

		ctx := WithUser(r.Context(), user)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
