package metrics

import (
	"strconv"
	"time"

	"git.frostfs.info/TrueCloudLab/frostfs-observability/metrics"
	"github.com/prometheus/client_golang/prometheus"
)

type MetabaseMetrics interface {
	SetMode(shardID, path string, mode string)
	Close(shardID, path string)

	MethodDuration(shardID, path string, method string, d time.Duration, success bool)
}

func newMetabaseMetrics() *metabaseMetrics {
	return &metabaseMetrics{
		mode: newShardIDPathMode(metabaseSubSystem, "mode", "Metabase mode"),
		reqDuration: metrics.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: metabaseSubSystem,
			Name:      "request_duration_seconds",
			Help:      "Accumulated Metabase request process duration",
		}, []string{shardIDLabel, successLabel, pathLabel, methodLabel}),
	}
}

type metabaseMetrics struct {
	mode        *shardIDPathModeValue
	reqDuration *prometheus.HistogramVec
}

func (m *metabaseMetrics) SetMode(shardID, path string, mode string) {
	m.mode.SetMode(shardID, path, mode)
}

func (m *metabaseMetrics) Close(shardID, path string) {
	m.mode.SetMode(shardID, path, closedMode)
	m.reqDuration.DeletePartialMatch(prometheus.Labels{
		shardIDLabel: shardID,
		pathLabel:    path,
	})
}

func (m *metabaseMetrics) MethodDuration(shardID, path string, method string, d time.Duration, success bool) {
	m.reqDuration.With(prometheus.Labels{
		shardIDLabel: shardID,
		pathLabel:    path,
		successLabel: strconv.FormatBool(success),
		methodLabel:  method,
	}).Observe(d.Seconds())
}