package com.zhentao.exception;

import com.zhentao.common.Result;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义错误控制器
 * 处理Spring Boot默认的/error路径
 */
@RestController
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<Result<String>> handleError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String errorMessage = (String) request.getAttribute("javax.servlet.error.message");
        Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");

        if (statusCode == null) {
            statusCode = 500;
        }

        if (errorMessage == null || errorMessage.isEmpty()) {
            if (statusCode == 404) {
                errorMessage = "请求的资源不存在";
            } else if (statusCode == 403) {
                errorMessage = "拒绝访问";
            } else if (statusCode == 401) {
                errorMessage = "未授权，请先登录";
            } else if (statusCode == 500) {
                errorMessage = "服务器内部错误";
            } else {
                errorMessage = "未知错误";
            }
        }

        if (exception != null && exception.getMessage() != null) {
            errorMessage = exception.getMessage();
        }

        Result<String> result = Result.error(statusCode, errorMessage);
        HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
        
        return new ResponseEntity<>(result, httpStatus);
    }
}

