package xtools.boot.web.filter.base;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.jspecify.annotations.NonNull;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * <p>Title : BaseFilter</p>
 * <p>Description : BaseFilter</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:06
 */
@Slf4j
public abstract class BaseFilter extends OncePerRequestFilter {

    /**
     * 跳过过滤器标识
     */
    private static final String SKIP_FILTER = "skip.filters";

    /**
     * 添加跳过过滤器标识
     *
     * @param request 请求
     */
    public void addSkipFilter(HttpServletRequest request) {
        request.setAttribute(SKIP_FILTER, true);
    }

    /**
     * 日志
     *
     * @param e   异常
     * @param msg 消息
     */
    public void printLog(Exception e, String msg) {
        if (e instanceof ClientAbortException) {
            return;
        }
        log.error(msg, e);
    }

    /**
     * 跳过过滤器
     *
     * @param request 请求
     * @return 是否跳过过滤器
     */
    @Override
    protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
        Object attribute = request.getAttribute(SKIP_FILTER);
        if (attribute instanceof Boolean skip) {
            return skip;
        }
        return false;
    }

}
