package xtools.boot.web.filter.common;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jspecify.annotations.NonNull;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import xtools.base.config.BaseParams;
import xtools.boot.core.interfaces.FilterWhitelist;
import xtools.boot.core.utils.PathPatternUtils;
import xtools.boot.core.utils.SpringContextUtils;
import xtools.boot.web.filter.base.BaseFilter;
import xtools.core.CollectionUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>Title : SkipFilter</p>
 * <p>Description : SkipFilter</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/3/8 11:00
 */
@Component
public class SkipFilter extends BaseFilter implements Ordered, BaseParams {

    /**
     * 白名单
     */
    private static final Set<String> WHITE_LIST = new HashSet<>();

    @Override
    public int getOrder() {
        return CP_NUM0;
    }

    @Override
    protected void initFilterBean() throws ServletException {
        super.initFilterBean();
        Collection<FilterWhitelist> beanList = SpringContextUtils.getBeanList(FilterWhitelist.class);
        if (CollectionUtils.isEmpty(beanList)) {
            return;
        }
        beanList.forEach(item -> WHITE_LIST.addAll(item.add()));
    }

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain
    ) throws ServletException, IOException {
        // 校验白名单
        if (PathPatternUtils.match(WHITE_LIST, request.getRequestURI())) {
            addSkipFilter(request);
        }
        filterChain.doFilter(request, response);
    }

}
