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;

/**
 * Dubbo提供者端Filter：从RpcContext接收Token并存储到ThreadLocal
 * 
 * @author yslg
 * @since 2025-12-20
 */
@Activate(group = CommonConstants.PROVIDER, order = -9000)
public class DubboProviderContextFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(DubboProviderContextFilter.class);
    private static final String AUTH_TOKEN_KEY = "auth-token";
    
    public static final ThreadLocal<String> TOKEN_HOLDER = new ThreadLocal<>();
    
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        try {
            // 从RpcContext获取消费者传递的Token
            String token = RpcContext.getServerAttachment().getAttachment(AUTH_TOKEN_KEY);
            
            if (StringUtils.hasText(token)) {
                // 存储到ThreadLocal供LoginUtil使用
                TOKEN_HOLDER.set(token);
                logger.debug("Dubbo提供者接收Token: {}", token.substring(0, Math.min(20, token.length())) + "...");
            }
            
            return invoker.invoke(invocation);
        } finally {
            // 清理ThreadLocal避免内存泄漏
            TOKEN_HOLDER.remove();
        }
    }
}
