package com.samsung.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
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;

@Component
@Profile("prod")
public class SslFilter extends OncePerRequestFilter {
    @Value("${ssl-port:443}")
    private String sslPort;

    @Override
    @SuppressWarnings({"jasper:id:issue:redirection", "jasper:id:issue:httpresponse"})
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();
        String protocol = request.getHeader("X-Forwarded-Proto");
        String domain = request.getServerName();
        String queryString = request.getQueryString();

        if (StringUtils.equals("http", protocol)) {
            response.setContentType(request.getContentType());
            //HTTPS 도메인 세팅 및 쿼리스트링 추가
            StringBuilder httpsPath = new StringBuilder("https" + "://" + domain + ":" + sslPort + url);
            if (StringUtils.isNotEmpty(queryString)) {
                httpsPath.append("?").append(queryString);
            }
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", httpsPath.toString());
        }
        filterChain.doFilter(request, response);
    }
}
