package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.fasterxml.jackson.core.JsonParseException;

import jakarta.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

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

    /**
     * 处理 JSON 解析错误
     * 这个异常通常是因为请求体中的 JSON 格式不正确
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, Object>> handleJsonParseException(
            HttpMessageNotReadableException ex,
            HttpServletRequest request) {

        logger.error("=== JSON 解析错误 ===");
        logger.error("请求URL: {}", request.getRequestURI());
        logger.error("请求方法: {}", request.getMethod());
        logger.error("Content-Type: {}", request.getContentType());
        logger.error("错误消息: {}", ex.getMessage());

        // 记录所有请求头
        logger.error("请求头:");
        request.getHeaderNames().asIterator().forEachRemaining(headerName -> {
            logger.error("  {}: {}", headerName, request.getHeader(headerName));
        });

        // 获取根本原因
        Throwable rootCause = ex.getRootCause();
        if (rootCause != null) {
            logger.error("根本原因: {}", rootCause.getMessage());
            if (rootCause instanceof JsonParseException) {
                JsonParseException jsonEx = (JsonParseException) rootCause;
                logger.error("JSON解析位置: line {}, column {}",
                    jsonEx.getLocation().getLineNr(),
                    jsonEx.getLocation().getColumnNr());
            }
        }

        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("success", false);
        errorResponse.put("message", "请求数据格式错误：JSON 格式不正确");
        errorResponse.put("error", "InvalidJsonFormat");
        errorResponse.put("details", "请检查发送的数据格式，确保是有效的 JSON");
        errorResponse.put("path", request.getRequestURI());

        if (rootCause != null && rootCause.getMessage() != null) {
            // 提取有用的错误信息，但不暴露太多内部细节
            String errorMsg = rootCause.getMessage();
            if (errorMsg.length() > 200) {
                errorMsg = errorMsg.substring(0, 200) + "...";
            }
            errorResponse.put("parseError", errorMsg);
        }

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
    }

    /**
     * 处理资源未找到异常 (404)
     * 通常是扫描器或错误的URL
     */
    @ExceptionHandler(org.springframework.web.servlet.resource.NoResourceFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNoResourceFoundException(
            org.springframework.web.servlet.resource.NoResourceFoundException e, 
            HttpServletRequest request) {
        
        // 这种错误通常不需要 ERROR 级别，WARN 即可，且不需要打印堆栈
        logger.warn("资源未找到 (404): {} {}", request.getMethod(), request.getRequestURI());
        
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("success", false);
        errorResponse.put("message", "未找到资源");
        errorResponse.put("path", request.getRequestURI());
        
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
    }

    /**
     * 处理不支持的请求方法异常（如 POST / 等）
     * 这类请求通常是扫描器或误操作，静默返回 405 即可
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<Map<String, Object>> handleMethodNotSupported(
            HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        // 仅记录简单日志，不输出详细堆栈
        logger.warn("不支持的请求方法: {} {}", request.getMethod(), request.getRequestURI());
        
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("success", false);
        errorResponse.put("message", "Method Not Allowed");
        errorResponse.put("path", request.getRequestURI());
        
        return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(errorResponse);
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e, HttpServletRequest request) {
        logger.error("全局异常处理器捕获到异常");
        logger.error("请求URL: {}", request.getRequestURI());
        logger.error("请求方法: {}", request.getMethod());
        logger.error("异常类型: {}", e.getClass().getName());
        logger.error("异常消息: {}", e.getMessage());
        if (e.getCause() != null) {
            logger.error("异常原因: {}", e.getCause().getMessage());
        }

        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("success", false);
        errorResponse.put("message", "服务器内部错误: " + e.getMessage());
        errorResponse.put("error", e.getClass().getSimpleName());
        errorResponse.put("path", request.getRequestURI());

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
    }
}


