// utils/imAuth/imRequest.js
// 专用于 IM 鉴权模块的请求封装
// 与 utils/request.js 功能完全一致，但不依赖 getApp()，API 域名硬编码
const API_BASE_URL = 'https://6ccy.top/hqhd';

function imRequest(options) {
  const token = wx.getStorageSync('token');
  const header = {
    'Content-Type': 'application/json',
    ...options.header,
  };
  if (token) {
    header['Authorization'] = 'Bearer ' + token;
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: API_BASE_URL + options.url,
      method: options.method,
      data: options.data || {},
      header,
      success: async (res) => {
        if (res.statusCode === 401 || res.statusCode === 403) {
          // 如果全局有登录 Promise 在等待，则等待完成后重试
          const app = getApp();
          if (app && app.globalData && app.globalData.loginPromise) {
            try {
              await app.globalData.loginPromise;
              const retryRes = await imRequest(options);
              resolve(retryRes);
            } catch (err) {
              wx.showModal({
                content: '操作失败，请先登录',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.removeStorageSync('token');
                    wx.switchTab({ url: '/pages/wode/wode' });
                  }
                },
              });
              resolve(res);
            }
            return;
          }

          // 常规未登录提示
          wx.showModal({
            content: '操作失败，请先登录',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.removeStorageSync('token');
                wx.switchTab({ url: '/pages/wode/wode' });
              }
            },
          });
          resolve(res);
          return;
        }
        // 正常响应
        resolve(res);
      },
      fail: reject,
    });
  });
}

module.exports = imRequest;