package metrics

import (
	"context"
	"net/url"
	"strings"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	clientmetrics "k8s.io/client-go/tools/metrics"
	"sigs.k8s.io/controller-runtime/pkg/metrics"
)

const (
	RestClientSubsystem = "rest_client"
	LatencyKey          = "request_latency_seconds"
)

//nolint:mnd // not need
var RequestLatency = prometheus.NewHistogramVec(prometheus.HistogramOpts{
	Subsystem: RestClientSubsystem,
	Name:      LatencyKey,
	Help:      "Request latency in seconds. Broken down by verb and URL.",
	Buckets:   prometheus.ExponentialBuckets(0.001, 2, 10),
}, []string{"verb", "url"})

func init() {
	metrics.Registry.MustRegister(RequestLatency)
	// force reset the metric for client-go
	clientmetrics.RequestLatency = &latencyAdapter{metric: RequestLatency}
}

// latencyAdapter implements LatencyMetric.
type latencyAdapter struct {
	metric *prometheus.HistogramVec
}

// Observe increments the request latency metric for the given verb/URL.
func (l *latencyAdapter) Observe(_ context.Context, verb string, u url.URL, latency time.Duration) {
	if strings.Contains(u.Path, "crossplane.io") {
		return
	}

	l.metric.WithLabelValues(verb, u.String()).Observe(latency.Seconds())
}
