package org.dromara.web.config;

import cn.dev33.satoken.exception.NotLoginException;
import org.dromara.app.domain.AppLoginUser;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * App用户信息补全过滤器
 *
 * @author Pair-Programmer
 */
public class AppInfoCompletionFilter implements Filter {

    @Value("#{'${app.auth.whitelist:/app/user/profile,/app/user/bind,/app/auth/logout}'.split(',')}")
    private List<String> whitelist;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String uri = httpRequest.getRequestURI();

        // 仅处理App端请求
        if (StringUtils.startsWith(uri, "/app")) {
            try {
                // 尝试获取登录用户，若未登录会抛出异常或返回null
                LoginUser loginUser = LoginHelper.getLoginUser();
                
                // 仅针对App登录用户进行检查
                if (loginUser instanceof AppLoginUser appUser) {
                    // 如果信息不完善 (infoComplete 为 false 或 null)
                    if (Boolean.FALSE.equals(appUser.getInfoComplete())) {
                        // 检查白名单
                        boolean isAllowed = false;
                        if (whitelist != null) {
                            for (String pattern : whitelist) {
                                if (pathMatcher.match(pattern.trim(), uri)) {
                                    isAllowed = true;
                                    break;
                                }
                            }
                        }

                        if (!isAllowed) {
                            ServletUtils.renderString((HttpServletResponse) response,
                                JsonUtils.toJsonString(R.fail(403, "用户信息未补全，请先完善信息")));
                            return;
                        }
                    }
                }
            } catch (Exception ignored) {
                // 未登录或其他异常（如Token无效），放行交由后续认证过滤器或拦截器处理
            }
        }

        chain.doFilter(request, response);
    }
}
