/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.config
 * @ClassName: RequestResponseWrapperConfig
 * @Description: 请求响应包装器配置类，包装HttpServletRequest和HttpServletResponse以支持内容缓存
 * @Author: 张志锋
 * @Date: 2025-10-31
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.config;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;

/**
 * 请求和响应包装器配置
 * 用于在拦截器中读取请求体和响应体
 */
@Component
public class RequestResponseWrapperConfig implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 不需要初始化
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uri = httpRequest.getRequestURI();
        if (uri.contains("/api/v1/files/stream/pdf") || uri.contains("/api/v1/files/preview/pdf")) {
            chain.doFilter(request, response);
            return;
        }

        // 包装请求和响应，以便可以多次读取内容
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(httpRequest);
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(httpResponse);

        try {
            chain.doFilter(wrappedRequest, wrappedResponse);
        } finally {
            // 确保响应内容被写入
            wrappedResponse.copyBodyToResponse();
        }
    }

    @Override
    public void destroy() {
        // 不需要清理
    }
}

