package com.css.simulation.resource.server.adapter.advice;

import api.common.pojo.common.ResponseBodyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class ExceptionHandlerControllerAdvice {
    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseBodyVO<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    /**
     * 请求体缺失异常统一处理
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseBodyVO<Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "Required request body is missing！");
    }


    /**
     * 权限校验异常统一处理
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseBodyVO<Object> handleAccessDeniedException(AccessDeniedException e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "Access is denied！");
    }

    /**
     * 权限校验异常统一处理
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseBodyVO<Object> handleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, e.getMessage());
    }

    /**
     * 服务器错误异常统一处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseBodyVO<Object> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "服务器错误！");
    }

}
