function getBridge() {
  const bridge = globalThis.__NAPCAT_BRIDGE__;
  if (!bridge) throw new Error('[QCE Overlay] Bridge未初始化');
  return bridge;
}

export const MsgApi = {
  async getMsgHistory(peer, msgId, count, reverse) {
    const { core } = getBridge();
    const impl = core?.apis?.MsgApi?.getMsgHistory || core?.apis?.msg?.getMsgHistory;
    if (!impl) throw new Error('[QCE Overlay] MsgApi.getMsgHistory 不可用');
    return impl.call(core.apis.MsgApi || core.apis.msg, peer, msgId, count, reverse);
  },

  async getAioFirstViewLatestMsgs(peer, count) {
    const { core } = getBridge();
    const impl = core?.apis?.MsgApi?.getAioFirstViewLatestMsgs || core?.apis?.msg?.getAioFirstViewLatestMsgs;
    if (!impl) throw new Error('[QCE Overlay] MsgApi.getAioFirstViewLatestMsgs 不可用');
    return impl.call(core.apis.MsgApi || core.apis.msg, peer, count);
  },

  async getMultiMsg(params) {
    const { core } = getBridge();
    const impl = core?.apis?.MsgApi?.getMultiMsg || core?.apis?.msg?.getMultiMsg;
    if (impl) return impl.call(core.apis.MsgApi || core.apis.msg, params);
    
    const { actions, instance } = getBridge();
    const handler = actions?.get?.('get_forward_msg');
    if (!handler) throw new Error('[QCE Overlay] get_forward_msg 不可用');
    const result = await handler.handle({ id: params.forwardId || params.resId }, 'plugin', instance?.config);
    return result?.data;
  }
};

export const NTQQMsgApi = MsgApi;
export default MsgApi;
