package httpapi

import (
	"net/http"
	"net/http/httptest"
	"testing"

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

func TestAuthorizeMetricsRequest(t *testing.T) {
	t.Parallel()
	gin.SetMode(gin.TestMode)

	createContext := func(headers map[string]string) (*gin.Context, *httptest.ResponseRecorder) {
		recorder := httptest.NewRecorder()
		context, _ := gin.CreateTestContext(recorder)
		request := httptest.NewRequest(http.MethodGet, "/v1/metrics", nil)
		for key, value := range headers {
			request.Header.Set(key, value)
		}
		context.Request = request
		return context, recorder
	}

	t.Run("allows when token unset", func(t *testing.T) {
		server := &Server{metricsToken: ""}
		context, _ := createContext(nil)
		if !server.authorizeMetricsRequest(context) {
			t.Fatal("expected request to pass when metrics token is unset")
		}
	})

	t.Run("accepts bearer token", func(t *testing.T) {
		server := &Server{metricsToken: "strong-metrics-token"}
		context, _ := createContext(map[string]string{
			"Authorization": "Bearer strong-metrics-token",
		})
		if !server.authorizeMetricsRequest(context) {
			t.Fatal("expected bearer token to authorize request")
		}
	})

	t.Run("accepts x metrics token", func(t *testing.T) {
		server := &Server{metricsToken: "strong-metrics-token"}
		context, _ := createContext(map[string]string{
			"X-Metrics-Token": "strong-metrics-token",
		})
		if !server.authorizeMetricsRequest(context) {
			t.Fatal("expected X-Metrics-Token to authorize request")
		}
	})

	t.Run("rejects invalid token", func(t *testing.T) {
		server := &Server{metricsToken: "strong-metrics-token"}
		context, recorder := createContext(map[string]string{
			"Authorization": "Bearer wrong-token",
		})
		if server.authorizeMetricsRequest(context) {
			t.Fatal("expected invalid token to be rejected")
		}
		if recorder.Code != http.StatusUnauthorized {
			t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
		}
	})
}
