package com.mini.capi.sys.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public Object handleError(HttpServletRequest request) {
        String uri = request.getRequestURI();

        // 1. 前端路由：统一转发到 index.html
        if (uri.startsWith("/cApi/index/")) {
            return "forward:/index.html";
        }

        // 2. 其他 404：返回 JSON
        HttpStatus status = getStatus(request);
        return ResponseEntity
                .status(status)
                .body(Map.of(
                        "status", status.value(),
                        "error", status.getReasonPhrase(),
                        "message", "访问的资源不存在",
                        "path", uri
                ));
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer code = (Integer) request.getAttribute("jakarta.servlet.error.status_code");
        return code != null ? HttpStatus.valueOf(code) : HttpStatus.INTERNAL_SERVER_ERROR;
    }
}