package org.wcs.serve.exception.handler;

import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.model.vo.serve.AppServeResponse;

import java.util.List;

/**
 * 系统的全局异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = {"org.wcs.serve.controller.app"})
public class AppExceptionHandler {

    /**
     * 接口层参数校验失败
     * @param ex 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public AppServeResponse handleException(MethodArgumentNotValidException ex) {
        log.info("接口层参数校验失败", ex);
        List<ObjectError> allErrors = ex.getAllErrors();
        if(allErrors.isEmpty()) {
            return AppServeResponseFactory.fail("接口层参数校验失败，未知异常");
        }
        return AppServeResponseFactory.fail(allErrors.getFirst().getDefaultMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public void handlerNotLoginException(NotLoginException nle) {
        // 未登录的直接返回 401 要求登录
        log.error("未登录异常:", nle);
    }

    /**
     * 兜底异常
     * @param ex 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AppServeResponse handleException(Exception ex) {
        log.error("系统异常", ex);
        return AppServeResponseFactory.fail("系统异常：" + ex.getMessage());
    }
}
