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;

        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);

    }

    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) {
            log.error("DevToolsIgnoreFilter Commit Error");
        }
    }
}
