package grpcli

import (
	"github.com/tidbcloud/pkgv2/bizerr"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// maxStandardGrpcCode is codes.Unauthenticated, the largest code gRPC itself
// defines. Anything above it was put there by a peer, not by the transport.
const maxStandardGrpcCode = codes.Unauthenticated

func GrpcStatus2BizError(s *status.Status) bizerr.BizError {
	// TiDB Cloud services return their bizerr code in the status code slot
	// rather than translating it down to a standard gRPC code, so a
	// "record not found" arrives as Code(49900004) instead of codes.NotFound.
	// Reading it back preserves the distinction; without this every such
	// answer collapses into ErrCodeUnknown and callers that branch on
	// not-found - the whole reuse-or-create idempotency pattern - never match.
	if s.Code() > maxStandardGrpcCode {
		return bizerr.New(bizerr.ErrCode(s.Code()), "%s", s.Message())
	}

	switch s.Code() {
	case codes.InvalidArgument:
		return bizerr.New(bizerr.ErrCodeParams, "%s", s.Message())
	case codes.NotFound:
		return bizerr.New(bizerr.ErrCodeRecordNotFound, "%s", s.Message())
	case codes.AlreadyExists:
		return bizerr.New(bizerr.ErrCodeRecordExist, "%s", s.Message())
	case codes.DeadlineExceeded:
		return bizerr.New(bizerr.ErrCodeTimeout, "%s", s.Message())
	case codes.Unauthenticated:
		return bizerr.New(bizerr.ErrCodeAuth, "%s", s.Message())
	case codes.PermissionDenied:
		return bizerr.New(bizerr.ErrCodePermission, "%s", s.Message())
	default:
		return bizerr.New(bizerr.ErrCodeUnknown, "%s", s.Message())
	}
}
