package monetix

import (
	"strings"
	"sync"
	"time"

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

var (
	metricsOnce sync.Once

	cardPayoutRequests  *prometheus.CounterVec
	cardPayoutCallbacks *prometheus.CounterVec
	cardPayoutLatency   *prometheus.HistogramVec
)

func initMetrics() {
	metricsOnce.Do(func() {
		cardPayoutRequests = promauto.NewCounterVec(prometheus.CounterOpts{
			Namespace: "sendico",
			Subsystem: "mcards_gateway",
			Name:      "card_payout_requests_total",
			Help:      "Monetix card payout submissions grouped by outcome.",
		}, []string{"outcome"})

		cardPayoutCallbacks = promauto.NewCounterVec(prometheus.CounterOpts{
			Namespace: "sendico",
			Subsystem: "mcards_gateway",
			Name:      "card_payout_callbacks_total",
			Help:      "Monetix card payout callbacks grouped by provider status.",
		}, []string{"status"})

		cardPayoutLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: "sendico",
			Subsystem: "mcards_gateway",
			Name:      "card_payout_request_latency_seconds",
			Help:      "Latency distribution for outbound Monetix card payout requests.",
			Buckets:   prometheus.DefBuckets,
		}, []string{"outcome"})
	})
}

func observeRequest(outcome string, duration time.Duration) {
	initMetrics()
	outcome = strings.ToLower(strings.TrimSpace(outcome))
	if outcome == "" {
		outcome = "unknown"
	}
	if cardPayoutLatency != nil {
		cardPayoutLatency.WithLabelValues(outcome).Observe(duration.Seconds())
	}
	if cardPayoutRequests != nil {
		cardPayoutRequests.WithLabelValues(outcome).Inc()
	}
}

// ObserveCallback records callback status for Monetix card payouts.
func ObserveCallback(status string) {
	initMetrics()
	status = strings.TrimSpace(status)
	if status == "" {
		status = "unknown"
	}
	status = strings.ToLower(status)
	if cardPayoutCallbacks != nil {
		cardPayoutCallbacks.WithLabelValues(status).Inc()
	}
}
