package metrics

import (
	"testing"
	"time"

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

func TestBusinessMetrics_Recorders(t *testing.T) {
	Init()
	const tenantID = "tenant-a"

	m := DefaultPrometheus()
	if m == nil {
		t.Fatal("expected Prometheus metrics to be initialized")
	}

	userBefore := testutil.ToFloat64(m.UserCreatedTotal.WithLabelValues(tenantID, "human"))
	IncUserCreated(tenantID, "human")
	if got := testutil.ToFloat64(m.UserCreatedTotal.WithLabelValues(tenantID, "human")); got != userBefore+1 {
		t.Fatalf("user_created_total: got %v, want %v", got, userBefore+1)
	}

	pushBefore := testutil.ToFloat64(m.GitPushTotal.WithLabelValues(tenantID))
	IncGitPush(tenantID)
	if got := testutil.ToFloat64(m.GitPushTotal.WithLabelValues(tenantID)); got != pushBefore+1 {
		t.Fatalf("git_push_total: got %v, want %v", got, pushBefore+1)
	}

	SetActiveUsersDaily(tenantID, 3)
	if got := testutil.ToFloat64(m.ActiveUsersDaily.WithLabelValues(tenantID)); got != 3 {
		t.Fatalf("active_users_daily: got %v, want 3", got)
	}

	ObserveUserActivationDuration(tenantID, 2*time.Minute)
	if got := testutil.CollectAndCount(m.UserActivationDuration); got == 0 {
		t.Fatal("expected user activation histogram to collect samples")
	}
}

func TestBusinessMetrics_DailyGaugesAreTenantScoped(t *testing.T) {
	Init()

	m := DefaultPrometheus()
	SetActiveUsersDaily("tenant-a", 2)
	SetActiveUsersDaily("tenant-b", 7)
	SetActiveReposDaily("tenant-a", 3)
	SetActiveReposDaily("tenant-b", 11)

	if got := testutil.ToFloat64(m.ActiveUsersDaily.WithLabelValues("tenant-a")); got != 2 {
		t.Fatalf("tenant-a active users = %v, want 2", got)
	}
	if got := testutil.ToFloat64(m.ActiveUsersDaily.WithLabelValues("tenant-b")); got != 7 {
		t.Fatalf("tenant-b active users = %v, want 7", got)
	}
	if got := testutil.ToFloat64(m.ActiveReposDaily.WithLabelValues("tenant-a")); got != 3 {
		t.Fatalf("tenant-a active repos = %v, want 3", got)
	}
	if got := testutil.ToFloat64(m.ActiveReposDaily.WithLabelValues("tenant-b")); got != 11 {
		t.Fatalf("tenant-b active repos = %v, want 11", got)
	}
}
