package org.mte.numecoeval.expositiondonneesentrees.infrastructure.handler;

import org.mte.numecoeval.expositiondonneesentrees.domain.exception.ReferentielRuntimeException;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;

public class RestClientResponseErrorHandler implements ResponseErrorHandler {

    private String errorType;
    private String errorMessage;

    public RestClientResponseErrorHandler(String errorType, String errorMessage) {
        this.errorType = errorType;
        this.errorMessage = errorMessage;
    }


    @Override
    public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
        return (httpResponse.getStatusCode().is4xxClientError() ||
                httpResponse.getStatusCode().is5xxServerError());
    }


    @Override
    public void handleError(ClientHttpResponse httpResponse) throws IOException {
        if (httpResponse.getStatusCode().is5xxServerError()) {
            //Handle SERVER_ERROR
                throw new ReferentielRuntimeException("ErrCalcTech","erreur serveur : "+httpResponse.getStatusText());

        }
        else if (httpResponse.getStatusCode().is4xxClientError()) {
            //Handle CLIENT_ERROR
                throw new ReferentielRuntimeException(errorType,errorMessage);
        }

    }
}
