package redis

import (
	telemetry "code.justin.tv/amzn/TwitchTelemetry"
	"code.justin.tv/creator-collab/log"
	"code.justin.tv/creator-collab/log/errors"
)

type rateLimitResult string

const (
	rateLimitResultAllow    = rateLimitResult("allow")
	rateLimitResultThrottle = rateLimitResult("throttle")
	rateLimitResultError    = rateLimitResult("error")
)

func newRateLimiterSampleReporter(sampleReporter *telemetry.SampleReporter, logWriter log.Logger) *rateLimiterSampleReporter {
	return &rateLimiterSampleReporter{
		sampleReporter: sampleReporter,
		logWriter:      logWriter,
	}
}

type rateLimiterSampleReporter struct {
	sampleReporter *telemetry.SampleReporter
	logWriter      log.Logger
}

func (r *rateLimiterSampleReporter) report(operation string, result rateLimitResult) {
	// Make a copy of the sample builder, and add the dimensions to it.
	sampleBuilder := r.sampleReporter.SampleBuilder
	if sampleBuilder.Dimensions == nil {
		sampleBuilder.Dimensions = make(telemetry.DimensionSet)
	}
	sampleBuilder.Dimensions["Operation"] = operation
	sampleBuilder.Dimensions["Result"] = string(result)

	sample, err := sampleBuilder.Build("OperationRateLimit", 1, telemetry.UnitCount)
	if err != nil {
		r.logWriter.Error(errors.Wrap(err, "building telemetry sample failed"))
		return
	}

	r.sampleReporter.ObserveSample(sample)
}
