package enea.lecservice.controllers.advice;

import enea.lecservice.models.dto.ServiceResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@RestControllerAdvice
public class ENEAAdvice extends ResponseEntityExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = { Exception.class, RuntimeException.class })
    public ServiceResponse unknownException(Exception ex, WebRequest req) {
        return ServiceResponse.Error(ex);
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = { BadCredentialsException.class })
    public ServiceResponse badCredentialException(Exception ex, WebRequest req) {
        return ServiceResponse.Error(ex);
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = { UsernameNotFoundException.class })
    public ServiceResponse notAuthorizedException(Exception ex, WebRequest req) {
        return ServiceResponse.Error(ex);
    }

    /*@ExceptionHandler(value = { ClientAbortException.class })
    public void clientAbortException(Exception ex, WebRequest request) {
        HttpServletRequest servletRequest = ((ServletWebRequest) request).getRequest();
        String clientIp = GlobalUtils.getClientIpFrom(servletRequest);
        log.error(String.format("OpenHR client abort: %s, Ip: %s", ex.getMessage(), clientIp));
    }*/
}
