package sqls

import (
	"strconv"
	"sync"
	"time"

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

var (
	httpRequestsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
		Namespace: "sqls",
		Name:      "http_requests_total",
		Help:      "Counter of HTTP requests for SQL Service.",
	}, []string{"method", "path"})

	httpDurationSeconds = prometheus.NewSummaryVec(prometheus.SummaryOpts{
		Namespace: "sqls",
		Name:      "http_duration_seconds",
		Help:      "Duration of HTTP requests for SQL Service.",
	}, []string{"method", "path", "status_code"})

	once sync.Once
)

// InitMetrics initializes the metrics for the SQL service.
// This function is idempotent and can be safely called multiple times.
func InitMetrics() {
	once.Do(func() {
		// Unregister any existing metrics with the same name to avoid conflicts
		prometheus.Unregister(httpRequestsTotal)
		prometheus.Unregister(httpDurationSeconds)

		// Register the metrics
		prometheus.MustRegister(httpRequestsTotal)
		prometheus.MustRegister(httpDurationSeconds)
	})
}

// recordHttpMetric records HTTP request metrics.
// It returns a function that should be deferred to record the duration.
func recordHttpMetric(c *gin.Context, path string) func() {
	// Ensure metrics are initialized
	InitMetrics()

	httpRequestsTotal.WithLabelValues(c.Request.Method, path).Inc()
	startTime := time.Now()

	return func() {
		duration := time.Since(startTime)
		httpDurationSeconds.WithLabelValues(
			c.Request.Method,
			path,
			strconv.Itoa(c.Writer.Status()),
		).Observe(duration.Seconds())
	}
}
