package metrics

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

func TestRegistryRendersCountersWithLabels(t *testing.T) {
	registry := NewRegistry()
	registry.AddCounter("vehicle_frames_total", Labels{"protocol": "JT808", "status": "ok"}, 2)
	registry.IncCounter("vehicle_frames_total", Labels{"status": "ok", "protocol": "JT808"})
	registry.IncCounter("vehicle_publish_errors_total", Labels{"target": "kafka"})

	text := registry.Render()

	for _, want := range []string{
		`# TYPE vehicle_frames_total counter`,
		`vehicle_frames_total{protocol="JT808",status="ok"} 3`,
		`# TYPE vehicle_publish_errors_total counter`,
		`vehicle_publish_errors_total{target="kafka"} 1`,
	} {
		if !strings.Contains(text, want) {
			t.Fatalf("metrics missing %s:\n%s", want, text)
		}
	}
}

func TestRegistryRendersGaugesWithLabels(t *testing.T) {
	registry := NewRegistry()
	registry.SetGauge("vehicle_gateway_connections", Labels{"protocol": "JT808"}, 2)
	registry.AddGauge("vehicle_gateway_connections", Labels{"protocol": "JT808"}, -1)
	registry.SetGauge("vehicle_gateway_connections", Labels{"protocol": "GB32960"}, 3)

	text := registry.Render()

	for _, want := range []string{
		`# TYPE vehicle_gateway_connections gauge`,
		`vehicle_gateway_connections{protocol="GB32960"} 3`,
		`vehicle_gateway_connections{protocol="JT808"} 1`,
	} {
		if !strings.Contains(text, want) {
			t.Fatalf("metrics missing %s:\n%s", want, text)
		}
	}
}

func TestRegistryObservesHistogramBuckets(t *testing.T) {
	registry := NewRegistry()

	registry.ObserveHistogram("vehicle_gateway_frame_duration_ms", Labels{"protocol": "JT808"}, []float64{1, 5, 10}, 7)

	text := registry.Render()
	for _, want := range []string{
		`# TYPE vehicle_gateway_frame_duration_ms histogram`,
		`vehicle_gateway_frame_duration_ms_bucket{le="1",protocol="JT808"} 0`,
		`vehicle_gateway_frame_duration_ms_bucket{le="5",protocol="JT808"} 0`,
		`vehicle_gateway_frame_duration_ms_bucket{le="10",protocol="JT808"} 1`,
		`vehicle_gateway_frame_duration_ms_bucket{le="+Inf",protocol="JT808"} 1`,
		`vehicle_gateway_frame_duration_ms_count{protocol="JT808"} 1`,
		`vehicle_gateway_frame_duration_ms_sum{protocol="JT808"} 7`,
	} {
		if !strings.Contains(text, want) {
			t.Fatalf("histogram missing %s:\n%s", want, text)
		}
	}
}

func TestRegistryRecordsKafkaLagGauge(t *testing.T) {
	registry := NewRegistry()

	registry.SetKafkaLag("vehicle_history_kafka_lag", "vehicle.raw.go.jt808.v1", 3, 101, 130)
	registry.SetKafkaLag("vehicle_history_kafka_lag", "vehicle.raw.go.gb32960.v1", 0, 9, 9)

	text := registry.Render()
	for _, want := range []string{
		`# TYPE vehicle_history_kafka_lag gauge`,
		`vehicle_history_kafka_lag{partition="0",topic="vehicle.raw.go.gb32960.v1"} 0`,
		`vehicle_history_kafka_lag{partition="3",topic="vehicle.raw.go.jt808.v1"} 28`,
	} {
		if !strings.Contains(text, want) {
			t.Fatalf("metrics missing %s:\n%s", want, text)
		}
	}
}

func TestRecordLastActivityRendersUnixGauge(t *testing.T) {
	registry := NewRegistry()

	RecordLastActivity(registry, "vehicle_stat_last_message_unix_seconds", Labels{"topic": "vehicle.fields.go.jt808.v1", "status": "received"})

	text := registry.Render()
	if !strings.Contains(text, `# TYPE vehicle_stat_last_message_unix_seconds gauge`) ||
		!strings.Contains(text, `vehicle_stat_last_message_unix_seconds{status="received",topic="vehicle.fields.go.jt808.v1"} `) {
		t.Fatalf("last activity gauge missing:\n%s", text)
	}
}

func TestRegisterServiceInfoRendersStableGauge(t *testing.T) {
	registry := NewRegistry()

	RegisterServiceInfo(registry, "vehicle-realtime-api")

	text := registry.Render()
	if !strings.Contains(text, `vehicle_service_info{service="vehicle-realtime-api"} 1`) {
		t.Fatalf("service info metric missing:\n%s", text)
	}
	for _, want := range []string{
		`# TYPE vehicle_process_start_time_unix_seconds gauge`,
		`# TYPE vehicle_process_uptime_seconds gauge`,
		`# TYPE vehicle_process_heap_alloc_bytes gauge`,
		`# TYPE vehicle_process_heap_sys_bytes gauge`,
		`# TYPE vehicle_process_goroutines gauge`,
		`vehicle_process_start_time_unix_seconds `,
		`vehicle_process_uptime_seconds `,
		`vehicle_process_heap_alloc_bytes `,
		`vehicle_process_heap_sys_bytes `,
		`vehicle_process_goroutines `,
	} {
		if !strings.Contains(text, want) {
			t.Fatalf("process runtime metric missing %s:\n%s", want, text)
		}
	}
}

func TestRegisterKafkaConsumerInfoRendersTopics(t *testing.T) {
	registry := NewRegistry()

	RegisterKafkaConsumerInfo(registry, "vehicle-stat-writer", "go-stat-writer", []string{
		"vehicle.fields.go.gb32960.v1",
		"vehicle.fields.go.jt808.v1",
		"",
	})

	text := registry.Render()
	for _, want := range []string{
		`vehicle_kafka_consumer_info{group="go-stat-writer",service="vehicle-stat-writer",topic="vehicle.fields.go.gb32960.v1"} 1`,
		`vehicle_kafka_consumer_info{group="go-stat-writer",service="vehicle-stat-writer",topic="vehicle.fields.go.jt808.v1"} 1`,
	} {
		if !strings.Contains(text, want) {
			t.Fatalf("consumer info metric missing %s:\n%s", want, text)
		}
	}
}

func TestHandlerServesPrometheusText(t *testing.T) {
	registry := NewRegistry()
	registry.IncCounter("vehicle_kafka_commits_total", Labels{"service": "history"})
	handler := NewHandler(registry)
	request := httptest.NewRequest(http.MethodGet, "/metrics", nil)
	response := httptest.NewRecorder()

	handler.ServeHTTP(response, request)

	if response.Code != http.StatusOK {
		t.Fatalf("status = %d body=%s", response.Code, response.Body.String())
	}
	if got := response.Header().Get("Content-Type"); !strings.Contains(got, "text/plain") {
		t.Fatalf("content-type = %q", got)
	}
	if !strings.Contains(response.Body.String(), `vehicle_kafka_commits_total{service="history"} 1`) {
		t.Fatalf("body = %s", response.Body.String())
	}
}

func TestHandlerRejectsNonMetricsPath(t *testing.T) {
	handler := NewHandler(NewRegistry())
	request := httptest.NewRequest(http.MethodGet, "/readyz", nil)
	response := httptest.NewRecorder()

	handler.ServeHTTP(response, request)

	if response.Code != http.StatusNotFound {
		t.Fatalf("status = %d", response.Code)
	}
}
