package com.jpsoft.shinestar.advice;

import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MessageResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage(),ex);

        String message = ex.getBindingResult().getFieldError().getDefaultMessage();

        MessageResult<String> messageResult = new MessageResult(false,message,null,500);

        return messageResult;
    }

    @ExceptionHandler(ValidationException.class)
    public MessageResult<String> handleValidationException(ValidationException ex) {
        log.error(ex.getMessage(),ex);

        String message = ex.getMessage();

        MessageResult<String> messageResult = new MessageResult(false,message,null,500);

        return messageResult;
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public MessageResult<String> handleConstraintViolationException(ConstraintViolationException ex) {
        log.error(ex.getMessage(),ex);

        String message = ex.getMessage();

        MessageResult<String> messageResult = new MessageResult(false,message,null,500);

        return messageResult;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public MessageResult<String> handleNoHandlerFoundException(Exception  ex) {
        log.error(ex.getMessage(),ex);

        String message = ex.getMessage();

        MessageResult<String> messageResult = new MessageResult(false,message,null,500);

        return messageResult;
    }

    @ExceptionHandler(RuntimeException.class)
    public MessageResult<String> handleRuntimeException(Exception  ex) {
        log.error(ex.getMessage(),ex);

        String message = ex.getMessage();

        MessageResult<String> messageResult = new MessageResult(false,message,null,500);

        return messageResult;
    }
}
