package httpapi

import (
	"crypto/subtle"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func (s *Server) authorizeMetricsRequest(c *gin.Context) bool {
	expectedToken := strings.TrimSpace(s.metricsToken)
	if expectedToken == "" {
		return true
	}

	providedToken := strings.TrimSpace(c.GetHeader("X-Metrics-Token"))
	if providedToken == "" {
		authHeader := strings.TrimSpace(c.GetHeader("Authorization"))
		if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
			providedToken = strings.TrimSpace(authHeader[len("Bearer "):])
		}
	}

	if subtle.ConstantTimeCompare([]byte(providedToken), []byte(expectedToken)) != 1 {
		s.writeStatusError(c, http.StatusUnauthorized, "valid metrics token required")
		return false
	}

	return true
}
