package opwrap

import "code.justin.tv/video/metrics-middleware/v2/operation"

const twitchS2S2OperationGroupName = "twitchs2s2"

// Statuses to be used
const (
	StatusUnknown int32 = 2
)

// GetAccessToken is when an access token is retrieved directly from
// the central servers instead of from cache.
var GetAccessToken = operation.Name{
	Kind:   operation.KindClient,
	Group:  twitchS2S2OperationGroupName,
	Method: "GetAccessToken",
}

// GetAssertion is when an assertion token is retrieved directly from the
// central servers instead of from cache.
var GetAssertion = operation.Name{
	Kind:   operation.KindClient,
	Group:  twitchS2S2OperationGroupName,
	Method: "GetAssertion",
}

// GetClientCredentials is when client credentials are retrieved directly from
// the central servers instead of from cache.
var GetClientCredentials = operation.Name{
	Kind:   operation.KindClient,
	Group:  twitchS2S2OperationGroupName,
	Method: "GetClientCredentials",
}

// GetOIDCConfiguration is when the OIDC configuration is retrieved directly
// from the cental servers.
var GetOIDCConfiguration = operation.Name{
	Kind:   operation.KindClient,
	Group:  twitchS2S2OperationGroupName,
	Method: "GetOIDCConfiguration",
}

// GetOIDCValidationKeys is when the validation keys are retrieved directly from
// the central servers.
var GetOIDCValidationKeys = operation.Name{
	Kind:   operation.KindClient,
	Group:  twitchS2S2OperationGroupName,
	Method: "GetOIDCValidationKeys",
}

// ServePassthroughRequest is when a client doesn't present an authorization
// header and authorization passthrough is enabled.
var ServePassthroughRequest = operation.Name{
	Kind:   operation.KindServer,
	Group:  twitchS2S2OperationGroupName,
	Method: "ServePassthroughRequest",
}

// ValidateAuthorization is when a server validates a new access token presented
// to it. Once validated, the access token and the results are stored in memory.
// If retrieved from cache, this metric will NOT be emitted again.
var ValidateAuthorization = operation.Name{
	Kind:   operation.KindServer,
	Group:  twitchS2S2OperationGroupName,
	Method: "ValidateAuthorization",
}

// EndWithError wraps an operation End with setting error status
func EndWithError(op *operation.Op, err error) {
	if err != nil {
		status := StatusUnknown
		if err, ok := err.(interface {
			StatusCode() int32
		}); ok {
			status = err.StatusCode()
		}
		op.SetStatus(operation.Status{Code: status})
	}
	op.End()
}
