/**
 * 消息对定义基类
 * 用于定义成对出现的请求和响应消息
 */
export abstract class MessagePair<TReq, TRes> {
    /** 请求消息名称 */
    abstract readonly requestName: string;

    /** 响应消息名称 */
    abstract readonly responseName: string;

    /** 请求消息类型检查 */
    abstract isValidRequest(msg: any): msg is TReq;

    /** 响应消息类型检查 */
    abstract isValidResponse(msg: any): msg is TRes;
}

/**
 * 消息对注册表
 * 用于管理所有的消息对
 */
export class MessagePairRegistry {
    private static _instance: MessagePairRegistry;
    private _pairs: Map<string, MessagePair<any, any>> = new Map();

    static getInstance(): MessagePairRegistry {
        if (!this._instance) {
            this._instance = new MessagePairRegistry();
        }
        return this._instance;
    }

    /**
     * 注册消息对
     * @param pair 消息对实例
     */
    register(pair: MessagePair<any, any>): void {
        this._pairs.set(pair.requestName, pair);
        console.log(`[MessagePairRegistry] Registered message pair: ${pair.requestName} -> ${pair.responseName}`);
    }

    /**
     * 根据请求消息名获取响应消息名
     * @param requestName 请求消息名
     * @returns 响应消息名，如果未找到返回null
     */
    getResponseName(requestName: string): string | null {
        const pair = this._pairs.get(requestName);
        return pair ? pair.responseName : null;
    }

    /**
     * 根据请求消息名获取消息对
     * @param requestName 请求消息名
     * @returns 消息对实例，如果未找到返回null
     */
    getPair(requestName: string): MessagePair<any, any> | null {
        return this._pairs.get(requestName) || null;
    }

    /**
     * 检查是否为已注册的请求消息
     * @param msgName 消息名
     */
    isRegisteredRequest(msgName: string): boolean {
        return this._pairs.has(msgName);
    }

    /**
     * 获取所有已注册的消息对
     */
    getAllPairs(): MessagePair<any, any>[] {
        return Array.from(this._pairs.values());
    }
}