package metrics

import "github.com/prometheus/client_golang/prometheus"

// ConnectionStat represents CQL client connection statistics for metrics export.
type ConnectionStat struct {
	Scope        string
	KeyspaceName string
	ClusterID    string
	Count        int
}

// ConnectionStatsProvider returns a snapshot of CQL client connection stats.
type ConnectionStatsProvider func() []ConnectionStat

type connectionStatsCollector struct {
	countDesc *prometheus.Desc
}

func newConnectionStatsCollector() *connectionStatsCollector {
	return &connectionStatsCollector{
		countDesc: prometheus.NewDesc(
			"proxy_cql_connection_count",
			"Current number of CQL client connections by scope.",
			[]string{"scope", "KeyspaceName", "ClusterId"},
			nil,
		),
	}
}

func (c *connectionStatsCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- c.countDesc
}

func (c *connectionStatsCollector) Collect(ch chan<- prometheus.Metric) {
	if c == nil {
		return
	}
	provider := activeConnectionStatsProvider()
	if provider == nil {
		return
	}
	stats := provider()
	for _, stat := range stats {
		scope := normalizeLabel(stat.Scope, "all")
		labels := MetricLabels{
			KeyspaceName: stat.KeyspaceName,
			ClusterID:    stat.ClusterID,
		}.withDefaults()
		ch <- prometheus.MustNewConstMetric(
			c.countDesc,
			prometheus.GaugeValue,
			float64(stat.Count),
			scope,
			labels.KeyspaceName,
			labels.ClusterID,
		)
	}
}
