package org.xyzh.common.auth.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.xyzh.common.auth.utils.LoginUtil;

/**
 * Dubbo消费者端Filter：自动传递登录Token到RpcContext
 * 
 * @author yslg
 * @since 2025-12-20
 */
@Activate(group = CommonConstants.CONSUMER, order = -9000)
public class DubboConsumerContextFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(DubboConsumerContextFilter.class);
    private static final String AUTH_TOKEN_KEY = "auth-token";
    
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 从当前HTTP请求获取Token
        String token = LoginUtil.getToken();
        
        if (StringUtils.hasText(token)) {
            // 将Token放入RpcContext，传递给提供者
            RpcContext.getClientAttachment().setAttachment(AUTH_TOKEN_KEY, token);
            logger.debug("Dubbo消费者传递Token: {}", token.substring(0, Math.min(20, token.length())) + "...");
        }
        
        return invoker.invoke(invocation);
    }
}
