package metrics

import "net/http"

// gRPC error codes taken from:
// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
const (
	grpcOK                 = 0
	grpcCancelled          = 1
	grpcUnknown            = 2
	grpcInvalidArgument    = 3
	grpcDeadlineExceeded   = 4
	grpcNotFound           = 5
	grpcAlreadyExists      = 6
	grpcPermissionDenied   = 7
	grpcResourceExhausted  = 8
	grpcFailedPrecondition = 9
	grpcUnimplemented      = 12
	grpcInternal           = 13
	grpcUnavailable        = 14
	grpcUnauthenticated    = 16
)

// httpStatusToGrpcCode converts an http status code to a Grpc error code.
// This is necessary because the TwitchTelemetry libraries expect Operation statuses to be Grpc error codes.
// The mapping is mostly taken from https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
func httpStatusToGrpcCode(code int) int32 {
	if code >= 200 && code < 300 {
		return grpcOK
	}

	switch code {
	case http.StatusBadRequest:
		return grpcInvalidArgument
	case http.StatusUnauthorized:
		return grpcUnauthenticated
	case http.StatusForbidden:
		return grpcPermissionDenied
	case http.StatusNotFound:
		return grpcNotFound
	case http.StatusConflict:
		return grpcAlreadyExists
	case http.StatusUnprocessableEntity:
		return grpcFailedPrecondition
	case http.StatusTooManyRequests:
		return grpcResourceExhausted
	case http.StatusInternalServerError:
		return grpcInternal
	case http.StatusNotImplemented:
		return grpcUnimplemented
	case http.StatusServiceUnavailable:
		return grpcUnavailable
	case http.StatusGatewayTimeout:
		return grpcDeadlineExceeded
	default:
		return grpcUnknown
	}
}
