package org.xyzh.common.exception.handler;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.exception.BusinessException;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description    全局异常处理器
 * @filename    GlobalExceptionHandler.java
 * @author    yslg
 * @copyright yslg
 * @since 2025-12-17
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleBusinessException(BusinessException e) {
        logger.warn("业务异常: {}", e.getMessage());
        return ResultDomain.failure(e.getCode(), e.getMessage());
    }

    /**
     * 参数校验异常 - @RequestBody 参数校验失败
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        logger.warn("参数校验失败: {}", message);
        return ResultDomain.failure(HttpStatus.BAD_REQUEST.value(), message);
    }

    /**
     * 参数校验异常 - @Validated 校验失败（方法参数直接校验）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String message = violations.stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("; "));
        logger.warn("参数校验失败: {}", message);
        return ResultDomain.failure(HttpStatus.BAD_REQUEST.value(), message);
    }

    /**
     * 参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleBindException(BindException e) {
        String message = e.getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        logger.warn("参数绑定失败: {}", message);
        return ResultDomain.failure(HttpStatus.BAD_REQUEST.value(), message);
    }

    /**
     * 缺少请求参数
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        String message = "缺少必要参数: " + e.getParameterName();
        logger.warn(message);
        return ResultDomain.failure(HttpStatus.BAD_REQUEST.value(), message);
    }

    /**
     * 缺少请求Part（multipart/form-data）
     */
    @ExceptionHandler(MissingServletRequestPartException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleMissingServletRequestPartException(MissingServletRequestPartException e) {
        String message = "缺少必要参数: " + e.getRequestPartName();
        logger.warn(message);
        return ResultDomain.failure(HttpStatus.BAD_REQUEST.value(), message);
    }

    /**
     * 文件上传大小超限
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        logger.warn("文件上传大小超限: {}", e.getMessage());
        return ResultDomain.failure(HttpStatus.BAD_REQUEST.value(), "上传文件大小超过限制");
    }

    /**
     * 权限不足异常
     */
    @ExceptionHandler(AuthorizationDeniedException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleAuthorizationDeniedException(AuthorizationDeniedException e) {
        logger.warn("权限不足: {}", e.getMessage());
        return ResultDomain.failure(HttpStatus.FORBIDDEN.value(), "权限不足");
    }

    /**
     * 其他未捕获异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultDomain<?> handleException(Exception e) {
        logger.error("系统异常: ", e);
        return ResultDomain.failure(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统异常，请联系管理员");
    }
}
