package middleware

import (
	"net/http"
	"strings"
)

// RequireBearerAuth returns middleware that rejects requests without a valid
// Authorization: Bearer <token> header. This prevents unauthenticated MCP
// clients from using the server's own ASTRA_API_KEY to call tools.
func RequireBearerAuth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		auth := r.Header.Get("Authorization")
		if len(auth) <= 7 || !strings.EqualFold(auth[:7], "Bearer ") || strings.TrimSpace(auth[7:]) == "" {
			w.Header().Set("WWW-Authenticate", `Bearer realm="mcp"`)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte(`{"error":"unauthorized","message":"Authorization: Bearer <token> header required"}`))
			return
		}
		next.ServeHTTP(w, r)
	})
}
