package com.smppw.modaq.infrastructure.components;

import cn.hutool.core.util.IdUtil;
import com.smppw.modaq.common.conts.Constants;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
@Order(1)
public class RequestIdFilter implements Filter {

    private static final String REQUEST_ID_HEADER = "X-Request-ID";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        try {
            // 尝试从Header获取RequestId，没有则生成
            String requestId = httpRequest.getHeader(REQUEST_ID_HEADER);
            if (!StringUtils.hasText(requestId)) {
                requestId = "REQ-" + IdUtil.simpleUUID();
            }

            MDC.put(Constants.MDC_REQUEST_ID_KEY, requestId);
            chain.doFilter(request, response);
        } finally {
            // 确保清除MDC
            MDC.remove(Constants.MDC_REQUEST_ID_KEY);
        }
    }
}
