package paymentapiimp

import (
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/mservice"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func grpcErrorResponse(logger mlogger.Logger, source mservice.Type, err error) http.HandlerFunc {
	statusErr, ok := status.FromError(err)
	if !ok {
		return response.Internal(logger, source, err)
	}

	switch statusErr.Code() {
	case codes.InvalidArgument:
		return response.BadRequest(logger, source, "invalid_argument", statusErr.Message())
	case codes.NotFound:
		return response.NotFound(logger, source, statusErr.Message())
	case codes.PermissionDenied:
		return response.AccessDenied(logger, source, statusErr.Message())
	case codes.Unauthenticated:
		return response.Unauthorized(logger, source, statusErr.Message())
	case codes.AlreadyExists, codes.Aborted:
		return response.DataConflict(logger, source, statusErr.Message())
	case codes.Unimplemented:
		return response.NotImplemented(logger, source, statusErr.Message())
	case codes.FailedPrecondition:
		return response.Error(logger, source, http.StatusPreconditionFailed, "failed_precondition", statusErr.Message())
	case codes.DeadlineExceeded:
		return response.Error(logger, source, http.StatusGatewayTimeout, "deadline_exceeded", statusErr.Message())
	case codes.Unavailable:
		return response.Error(logger, source, http.StatusServiceUnavailable, "service_unavailable", statusErr.Message())
	default:
		return response.Internal(logger, source, err)
	}
}
