package com.eactive.eai.rms.common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CrossScriptingFilter implements Filter {

	private static final Log logger = LogFactory.getLog(CrossScriptingFilter.class);

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void destroy() {

	}

	/**
	 * 프록시 환경을 고려하여 baseUrl을 구합니다.
	 * X-Forwarded-Proto, X-Forwarded-Host 헤더가 있으면 우선 사용합니다.
	 */
	private String getBaseUrl(HttpServletRequest request) {
		String forwardedProto = request.getHeader("X-Forwarded-Proto");
		String forwardedHost = request.getHeader("X-Forwarded-Host");

		if (forwardedProto != null && forwardedHost != null) {
			// 프록시 환경: X-Forwarded 헤더 사용
			String baseUrl = forwardedProto + "://" + forwardedHost;
			// :443 포트 제거 (https 기본 포트)
			baseUrl = baseUrl.replace(":443", "");
			return baseUrl;
		}

		// 직접 접속: 기존 로직
		String uri = request.getRequestURL().toString();
		String servletPath = request.getServletPath();
		String baseUrl = uri.replace(servletPath, "");
		return baseUrl;
	}

	private boolean checkReturnUrl(HttpServletRequest request, String returnUrl) {
		String baseUrl = getBaseUrl(request);
		// 25.11.10 - weblogic https://host:443/ 문제 대응
		baseUrl = baseUrl.replace(":443", "");

		if (logger.isDebugEnabled()) {
			logger.debug("checkReturnUrl - baseUrl: " + baseUrl + ", returnUrl: " + returnUrl);
		}

		return returnUrl.startsWith(baseUrl);
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		String returnUrl = (String) request.getParameter("returnUrl");
		if (returnUrl != null) {
			if (!checkReturnUrl(request, returnUrl)) {
				logger.warn("returnUrl validation failed - baseUrl: " + getBaseUrl(request)
						+ ", returnUrl: " + returnUrl
						+ ", X-Forwarded-Proto: " + request.getHeader("X-Forwarded-Proto")
						+ ", X-Forwarded-Host: " + request.getHeader("X-Forwarded-Host"));
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bad request. - " + returnUrl);
				return;
			}
		}

		// Web Cache Deception
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);

		chain.doFilter(new RequestWrapper(request), response);
//    	
//    	if(servletPath.startsWith("/onl/admin/common")) {
//    		System.out.println("RequestWrapper called");
//    		chain.doFilter(new RequestWrapper(request), response);
//    	}
//    	else {
//    		chain.doFilter(request, response);
//    	}
	}

}
