package com.liquidnet.common.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class GlobalLogTrackInterceptor extends HandlerInterceptorAdapter {
    private static final String LNS_TRANCE_ID = "lnsTranceId";
    private static final String X_SERVER_HEADER = "X-Server";
    private static final String POD_NAME_ENV = "POD_NAME";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String t = MDC.get(LNS_TRANCE_ID);
        MDC.put(LNS_TRANCE_ID, null == t ? String.valueOf(System.nanoTime()) : t);
        
        // 从环境变量获取POD_NAME并添加到响应头
        String podName = System.getenv(POD_NAME_ENV);
        if (podName != null && !podName.isEmpty()) {
//            log.info("[preHandle] podName: {}", podName);
            response.setHeader(X_SERVER_HEADER, podName);
        }
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long e = Long.parseLong(MDC.get(LNS_TRANCE_ID));
        log.info("[{}]耗时:{}ms", request.getRequestURI(), (System.nanoTime() - e) / 1000000);
        MDC.clear();
    }
}
