package cn.yunzhixue.ability.center;

import cn.yunzhixue.ability.center.kernel.BaseResponse;
import cn.yunzhixue.ability.center.kernel.BusinessException;
import cn.yunzhixue.ability.center.kernel.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<BaseResponse<Void>> handleBusinessException(BusinessException exception) {
        return ResponseEntity
                .status(HttpStatusCode.valueOf(exception.getErrorCode().getHttpStatusCode()))
                .body(BaseResponse.failure(exception.getErrorCode(), exception.getMessage()));
    }

    @ExceptionHandler({
            MissingServletRequestParameterException.class,
            MethodArgumentNotValidException.class,
            BindException.class,
            HttpMessageNotReadableException.class})
    public ResponseEntity<BaseResponse<Void>> handleValidationException(Exception exception) {
        return ResponseEntity
                .status(HttpStatusCode.valueOf(ErrorCode.VALIDATION_ERROR.getHttpStatusCode()))
                .body(BaseResponse.failure(
                        ErrorCode.VALIDATION_ERROR,
                        "请求体不是合法 JSON，或请求参数格式不正确"));
    }

    @ExceptionHandler({NoHandlerFoundException.class, NoResourceFoundException.class})
    public ResponseEntity<BaseResponse<Void>> handleNotFoundException(Exception exception) {
        return ResponseEntity.notFound().build();
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<BaseResponse<Void>> handleException(Exception exception) {
        log.error("Unhandled exception caught by global handler", exception);
        return ResponseEntity
                .status(HttpStatusCode.valueOf(ErrorCode.INTERNAL_ERROR.getHttpStatusCode()))
                .body(BaseResponse.failure(ErrorCode.INTERNAL_ERROR));
    }
}
