package com.ruoyi.system.utils;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;

/**
 * 读取认证切面写入当前请求的可信身份信息。
 *
 * <p>该上下文不解析或重新验证客户端 Token，避免业务 Controller 重复执行认证逻辑。</p>
 */
public final class AuthContext {

    public static final String USER_ID_ATTRIBUTE = AuthContext.class.getName() + ".userId";
    public static final String JTI_ATTRIBUTE = AuthContext.class.getName() + ".jti";

    private AuthContext() {
    }

    public static Long requireUserId() {
        Object value = ServletUtils.getRequest().getAttribute(USER_ID_ATTRIBUTE);
        if (value instanceof Long userId) {
            return userId;
        }
        throw unauthorized();
    }

    public static String requireJti() {
        Object value = ServletUtils.getRequest().getAttribute(JTI_ATTRIBUTE);
        if (value instanceof String jti && !jti.isBlank()) {
            return jti;
        }
        throw unauthorized();
    }

    private static ServiceException unauthorized() {
        return new ServiceException(MessageUtils.message("merchant.session.invalid"));
    }
}
