package observability

import (
	telemetry "code.justin.tv/amzn/TwitchTelemetry"

	"code.justin.tv/eventbus/controlplane/internal/db"
	"code.justin.tv/eventbus/controlplane/internal/metrics"
)

const (
	queryLatency     = "QueryLatency"
	querySuccess     = "QuerySuccess"
	queryError       = "QueryError"
	queryClientError = "QueryClientError"
)

// Best effort metric submission
func submitMetrics(obsData *observabilityData) {
	sampleObserver := metrics.Observer()
	procID := metrics.ProcessIdentifier()

	var success int
	var error int
	var clientError int
	if obsData.err != nil {
		error = 1
		success = 0
		clientError = 0
	} else if obsData.err == db.ErrResourceNotFound { // 4XX style "NotFound" errors due to bad client requests
		error = 0
		success = 0
		clientError = 1
	} else {
		error = 0
		success = 1
		clientError = 0
	}

	sampleBuilder := &telemetry.SampleBuilder{
		ProcessIdentifier: procID,
		OperationName:     obsData.action,
	}

	// create and submit 3 samples per operation
	latencySample, err := sampleBuilder.BuildDurationSample(queryLatency, obsData.end.Sub(obsData.start))
	if err == nil {
		sampleObserver.ObserveSample(latencySample)
	}

	successSample, err := sampleBuilder.Build(querySuccess, float64(success), telemetry.UnitCount)
	if err == nil {
		sampleObserver.ObserveSample(successSample)
	}

	errorSample, err := sampleBuilder.Build(queryError, float64(error), telemetry.UnitCount)
	if err == nil {
		sampleObserver.ObserveSample(errorSample)
	}

	clientErrorSample, err := sampleBuilder.Build(queryClientError, float64(clientError), telemetry.UnitCount)
	if err == nil {
		sampleObserver.ObserveSample(clientErrorSample)
	}
}
