package com.czg.mqtt.manager;

import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * MQTT 订阅关系管理器（单例，所有 Handler 共享）
 *
 * @author yjjie
 */
@Component
public class MqttSubscriptionManager {
    // 主题 -> 订阅的客户端 Channel（线程安全）
    private final ConcurrentMap<String, Set<Channel>> topicSubscribers = new ConcurrentHashMap<>();

    // 添加订阅（主题-客户端绑定）
    public void addSubscription(String topic, Channel channel) {
        topicSubscribers.computeIfAbsent(topic, k -> ConcurrentHashMap.newKeySet())
                .add(channel);
    }

    // 移除订阅（客户端断开时调用）
    public void removeSubscription(String topic, Channel channel) {
        Set<Channel> channels = topicSubscribers.get(topic);
        if (channels != null) {
            channels.remove(channel);
            if (channels.isEmpty()) {
                topicSubscribers.remove(topic);
            }
        }
    }

    // 移除客户端的所有订阅（客户端断开时调用）
    public void removeAllSubscriptions(Channel channel) {
        topicSubscribers.forEach((topic, channels) -> channels.remove(channel));
    }

    // 获取主题的所有订阅者
    public Set<Channel> getSubscribers(String topic) {
        return topicSubscribers.getOrDefault(topic, Set.of());
    }
}
