package com.devjob.job.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

/**
 * EP22: 응답에 이 인스턴스가 어느 포트에서 떠 있는지 헤더로 표시한다.
 *
 * devjob-job을 여러 포트(8082, 8085 ...)로 동시에 띄워놓고 Gateway/@HttpExchange을
 * 통해 반복 호출했을 때, 어떤 인스턴스가 응답했는지 한눈에 확인하기
 * 위한 용도다 (로드밸런싱 데모).
 */
@Component
public class InstanceInfoFilter extends GenericFilterBean {

    private final String port;

    public InstanceInfoFilter(@Value("${server.port}") String port) {
        this.port = port;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ((HttpServletResponse) response).setHeader("X-Instance-Port", port);
        chain.doFilter(request, response);
    }
}
