package com.bio.bio_backend.global.filter;

import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Component
@Order(1)
public class TraceIdFilter extends OncePerRequestFilter {

    private static final String TRACE_ID_HEADER = "X-Trace-Id";
    private static final String TRACE_ID_MDC_KEY = "traceId";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        try {
            // 헤더에서 TRACE ID를 가져오거나 새로 생성
            String traceId = request.getHeader(TRACE_ID_HEADER);
            if (traceId == null || traceId.trim().isEmpty()) {
                traceId = generateTraceId();
            }
            
            // MDC에 TRACE ID 설정
            MDC.put(TRACE_ID_MDC_KEY, traceId);
            
            // 응답 헤더에 TRACE ID 추가
            response.addHeader(TRACE_ID_HEADER, traceId);
            
            filterChain.doFilter(request, response);
            
        } finally {
            // 요청 처리 완료 후 MDC 정리
            MDC.remove(TRACE_ID_MDC_KEY);
        }
    }

    private String generateTraceId() {
        // UUID 기반 TRACE ID 생성 (8자리로 축약)
        return UUID.randomUUID().toString().substring(0, 8);
    }
}
