package pwc.taxtech.atms.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import pwc.taxtech.atms.exception.ApplicationException;
import pwc.taxtech.atms.exception.ServiceException;

@ControllerAdvice
public class AtmsExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {
            ApplicationException.class,
            ServiceException.class
    })
    protected ResponseEntity<Object> handleExceptions(Exception ex) throws ServiceException {
        logger.error("Rest Exception!", ex);
        if (ex instanceof ApplicationException) {
            return handleApplicationException((ApplicationException) ex);
        } else if (ex instanceof ServiceException) {
            return handleServiceException((ServiceException) ex);
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    private ResponseEntity<Object> handleApplicationException(ApplicationException ex) {
        throw ex;
    }

    private ResponseEntity<Object> handleServiceException(ServiceException ex) throws ServiceException {
        throw ex;
    }

}