package com.tsi.monitoring.config;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

//@Configuration
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DevToolsIgnoreFilter implements Filter {

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

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        try {
            String uri = request.getRequestURI();

            // 크롬 개발자 도구 자동 요청 및 특정 경로 무시
            if (uri.contains(".well-known") || uri.contains("/json") || uri.contains("/devtools")  || uri.contains("/spring-boot-livereload")) {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"status\": \"ok\", \"message\": \"Chrome DevTools auto request ignored\"}");
                response.getWriter().flush();
                return; // 여기서 종료
            }

            // 정상 요청은 다음 Filter / Controller로 전달
            chain.doFilter(request, response);

        } catch (Throwable ex) {
            // Filter 단계에서 발생할 수 있는 모든 예외 잡기
            if (!response.isCommitted()) {
                sendJsonResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "{\"status\": \"error\", \"message\": \"서버 오류 발생\"}");
            } else {
                // 이미 응답 커밋됨 → 로그만 기록, 외부로 던지지 않음
                log.error("Filter 단계 예외 발생 (이미 응답 커밋됨): {}", ex.getMessage());
            }
        }
    }

    private void sendJsonResponse(HttpServletResponse response, int status, String json) {
        try {
            response.setStatus(status);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);
            response.getWriter().flush();
        } catch (IOException ignored) {
            // 이미 응답이 커밋된 경우 무시
        }
    }
}
