package twirperr

import (
	"github.com/pkg/errors"
	"github.com/twitchtv/twirp"
)

func Convert(err error) twirp.Error {
	dbError, ok := errors.Cause(err).(DBError)
	if ok {
		switch {
		case dbError.DuplicateSubscriptionTargetQueueURL():
			return twirp.WrapError(twirp.NewError(twirp.InvalidArgument, msgDuplicateSubscriptionTargetQueueURL), err)
		case dbError.DuplicateIAMRoleARN():
			return twirp.WrapError(twirp.NewError(twirp.InvalidArgument, msgDuplicateIAMRoleARN), err)
		case dbError.DuplicateIAMRoleLabelForService():
			return twirp.WrapError(twirp.NewError(twirp.InvalidArgument, msgDuplicateIAMRoleLabelForService), err)
		case dbError.DuplicateServiceCatalogID():
			return twirp.WrapError(twirp.NewError(twirp.InvalidArgument, msgDuplicateServiceCatalogID), err)
		case dbError.EventTypeNotFound():
			return twirp.WrapError(twirp.NewError(twirp.NotFound, msgEventTypeNotFound), err)
		case dbError.IAMRoleNotFound():
			return twirp.WrapError(twirp.NewError(twirp.NotFound, msgIAMRoleNotFound), err)
		case dbError.ServiceNotFound():
			return twirp.WrapError(twirp.NewError(twirp.NotFound, msgServiceNotFound), err)
		case dbError.SubscriptionTargetNotFound():
			return twirp.WrapError(twirp.NewError(twirp.NotFound, msgSubscriptionTargetNotFound), err)
		}
	}

	// In a future refactoring of error handling, there could be another large class of errors to create an interface for
	// and handle in a similar way to DBError. That would live here and result in another switch statement to work through
	// before falling back to an "internal server error" 500.

	return twirp.WrapError(twirp.InternalError(msgInternalServerError), err)
}
