package me.qwq.doghouse.interceptions;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ThemeStaticFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 只对 URI（不含 query）做判断
        String uri = req.getRequestURI();

        // 去掉 context-path（应用部署在 /xxx 时必须处理）
        String ctx = req.getContextPath();
        if (ctx != null && !ctx.isEmpty() && uri.startsWith(ctx)) {
            uri = uri.substring(ctx.length());
        }

        // 仅处理 /themes/...，其它放行
        if (!uri.startsWith("/themes/")) {
            chain.doFilter(request, response);
            return;
        }

        // 规范化：合并重复斜杠，去掉尾部斜杠（可选）
        uri = uri.replaceAll("/{2,}", "/");

        // 按路径段切分
        List<String> segs = splitSegments(uri);

        // 期望至少：themes/{theme}/static/...
        // segs[0]=themes, segs[1]=themeName, segs[2]=static
        boolean allowed = segs.size() >= 3
                && "themes".equals(segs.get(0))
                && "static".equals(segs.get(2))
                // 基本的穿越拦截（额外保险）
                && segs.stream().noneMatch(s -> s.equals("..") || s.contains("\0") || s.contains("\b"));

        if (!allowed) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        chain.doFilter(request, response);
    }

    private static List<String> splitSegments(String path) {
        // 输入类似：/themes/bleaching/static/css/main.css
        String[] raw = path.split("/");
        List<String> segs = new ArrayList<>();
        for (String s : raw) {
            if (s == null || s.isEmpty()) continue;
            segs.add(s);
        }
        return segs;
    }
}
