package org.dromara.web.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dromara.common.core.domain.R;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 风险控制拦截器
 *
 * @author Pair-Programmer
 */
public class RiskInterceptor implements HandlerInterceptor {

    public static final String RISK_LOCKED_KEY = "RISK_LOCKED";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 仅处理登录用户
        if (!StpUtil.isLogin()) {
            return true;
        }

        // 检查 Session 是否有风险锁
        Object isLocked = StpUtil.getSession().get(RISK_LOCKED_KEY);
        if (ObjectUtil.isNotNull(isLocked) && (Boolean) isLocked) {
            String uri = request.getRequestURI();
            
            // 白名单：改密接口、登出接口、获取个人信息(用于页面展示)
            // 注意：具体路径需根据实际 Controller 调整
            if (StringUtils.equalsAnyIgnoreCase(uri, 
                "/system/user/profile/updatePwd", 
                "/auth/logout",
                "/system/user/profile"
            )) {
                return true;
            }

            // 拦截并返回 403
            ServletUtils.renderString(response, 
                JsonUtils.toJsonString(R.fail(403, "检测到异常登录，请强制修改密码后继续操作")));
            return false;
        }

        return true;
    }
}
