package com.yaoyuan.jiscuss.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * Handles 403 access-denied responses.
 *
 * <p>Behavior:
 * <ul>
 *   <li>AJAX requests → JSON body with {@code code/msg}</li>
 *   <li>Regular page requests → simple HTML 403 response (no forward to /403,
 *       which previously caused a 404)</li>
 * </ul>
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

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

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (response.isCommitted()) {
            return;
        }

        log.warn("Access denied for {} → {}", request.getRequestURI(), accessDeniedException.getMessage());
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setCharacterEncoding("UTF-8");

        if (isAjaxRequest(request)) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            try (PrintWriter writer = response.getWriter()) {
                writer.write("{\"code\":403,\"msg\":\"没有权限\"}");
            }
        } else {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            try (PrintWriter writer = response.getWriter()) {
                writer.write("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>403 Forbidden</title></head>"
                        + "<body><h1>403 Forbidden</h1><p>您没有权限访问该资源。</p></body></html>");
            }
        }
    }

    private static boolean isAjaxRequest(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}

