package runtimeprocess

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

	"github.com/prometheus/client_golang/prometheus"
)

// TestAdditionalMetricsCollectorsAreServed exists because this registry is private: a metric
// registered on the default registry is invisible here, so anything an operator must see has to be
// handed over explicitly. The single collector slot was already taken by the records server, and a
// second owner displacing it would have made one of them silently absent — which review found as
// the empty-scope inventory reporting nothing in this process.
func TestAdditionalMetricsCollectorsAreServed(t *testing.T) {
	extra := prometheus.NewCounterVec(
		prometheus.CounterOpts{Name: "nexuscrm_test_additional_collector_total", Help: "test"},
		[]string{"label"},
	)
	extra.WithLabelValues("value").Inc()

	process := &Process{config: Config{
		AdditionalMetricsCollectors: []prometheus.Collector{extra},
	}}
	handler, err := newMetricsHandler(process)
	if err != nil {
		t.Fatalf("newMetricsHandler: %v", err)
	}

	response := httptest.NewRecorder()
	handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
	if !strings.Contains(response.Body.String(), "nexuscrm_test_additional_collector_total") {
		t.Fatal("an additional collector was not served, so a metric handed to this process would be invisible")
	}
}

// TestANilAdditionalCollectorIsSkipped keeps an optional collector from failing the boot. A process
// that will not start because a metric is absent is worse than the missing metric.
func TestANilAdditionalCollectorIsSkipped(t *testing.T) {
	process := &Process{config: Config{
		AdditionalMetricsCollectors: []prometheus.Collector{nil},
	}}
	if _, err := newMetricsHandler(process); err != nil {
		t.Fatalf("a nil additional collector failed the metrics handler: %v", err)
	}
}
