package com.sikey.wa04.common.filter;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.sikey.wa04.common.constants.HeaderConstant;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RequestIdFilter implements Filter {

    /**
     * RequestId
     *
     * @param servletRequest  请求
     * @param servletResponse 响应
     * @param filterChain     过滤器链
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String requestId = UUID.randomUUID().toString();

        // 如果已经有了 requestId，就不再生成
        if (servletRequest instanceof HttpServletRequest request) {
            String xRequestId = request.getHeader(HeaderConstant.REQUEST_ID);
            if (StrUtil.isNotEmpty(xRequestId)) {
                requestId = xRequestId;
            }
        }

        MDC.put("requestId", requestId);
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
