package com.kingdee.eas.custom.integration.base.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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 java.io.IOException;

/**
 * Apusic 外部 GET 常需走 *.do；把 /auth 下无后缀路径 forward 到同名 .do。
 * 浏览器地址可保持无 .do（回调注册不用改），内部落到 DispatcherServlet 的 *.do 映射。
 */
public class CallbackSuffixCompatFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(CallbackSuffixCompatFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String servletPath = resolveServletPath(httpRequest);
        if (servletPath.endsWith(".do")) {
            chain.doFilter(request, response);
            return;
        }

        if (servletPath.startsWith("/auth/")) {
            String compatPath = servletPath + ".do";
            log.info("auth path suffix compat: {} -> {} (query={})",
                    servletPath, compatPath, httpRequest.getQueryString());
            httpRequest.getRequestDispatcher(compatPath).forward(httpRequest, httpResponse);
            return;
        }

        chain.doFilter(request, response);
    }

    private String resolveServletPath(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        if (servletPath != null && !servletPath.isEmpty()) {
            return servletPath;
        }
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        if (contextPath != null && !contextPath.isEmpty() && uri.startsWith(contextPath)) {
            return uri.substring(contextPath.length());
        }
        return uri;
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
