class ResponseHandlers {

    public static <T> HttpClient.ResponseHandler<T> consentCreationResponseHandler(String scaOAuthUrl, Class<T> klass) {
        return (statusCode, responseBody, responseHeaders) -> {
            if (statusCode == 401 || statusCode == 403) {
                String contentType = responseHeaders.getHeader(RequestHeaders.CONTENT_TYPE);
                PushbackInputStream pushbackResponseBody = new PushbackInputStream(responseBody);

                // this statement is needed as error response handling is different from the successful response
                if ((contentType == null || !contentType.startsWith(APPLICATION_JSON)) && isNotJson(pushbackResponseBody)) {
                    // needed to avoid org.springframework.http.converter.HttpMessageNotWritableException:
                    // No converter for [class de.adorsys.xs2a.adapter.api.model.ErrorResponse]
                    // with preset Content-Type 'application/xml;charset=UTF-8'
                    Map<String, String> headersMap = responseHeaders.getHeadersMap();
                    headersMap.put(ResponseHeaders.CONTENT_TYPE, APPLICATION_JSON);

                    throw oAuthException(pushbackResponseBody, ResponseHeaders.fromMap(headersMap), scaOAuthUrl,
                        ResponseHandlers::buildErrorResponseForOAuthNonJsonCase);
                }

                throw oAuthException(pushbackResponseBody, responseHeaders, scaOAuthUrl,
                    ResponseHandlers::buildErrorResponseFromString);
            }

            return jsonResponseHandler(klass)
                       .apply(statusCode, responseBody, responseHeaders);
        };
    }

    private  ResponseHandlers();

}