package com.huangzj.base.cmd;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局 PB 命令表：按「链路 + service + method」注册 {@link ProtoInfo}，网络层只查这里拿类型。
 */
@Component
public class ProtoRegistry {

    private final ConcurrentHashMap<String, ProtoInfo> byKey = new ConcurrentHashMap<>();

    public void register(ProtoInfo info) {
        String k = key(info.source(), info.serviceId(), info.methodId());
        ProtoInfo prev = byKey.putIfAbsent(k, info);
        if (prev != null) {
            throw new IllegalStateException("ProtoInfo 重复注册: " + k + " 已有 " + prev);
        }
    }

    /**
     * 未注册时返回 null（例如纯透传、自定义解析的命令）。
     */
    public ProtoInfo resolve(CommandSource source, int serviceId, int methodId) {
        return byKey.get(key(source, serviceId, methodId));
    }

    private static String key(CommandSource source, int serviceId, int methodId) {
        return source.name() + ":" + serviceId + ":" + methodId;
    }
}
