// utils/request.js
import { buildClubHeaders } from './club-context';

function request(options) {
  const app = getApp();
  const token = wx.getStorageSync('token');

  if (!token) {
    return Promise.resolve({
      statusCode: 401,
      data: { code: 401, msg: '未登录' },
      errMsg: 'request:ok'
    });
  }

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

  return new Promise((resolve, reject) => {
    wx.request({
      url: app.globalData.apiBaseUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header,
      timeout: options.timeout || 15000,
      success: async (res) => {
        if (res.statusCode === 401 || res.statusCode === 403) {
          if (app.globalData.loginPromise) {
            try {
              await app.globalData.loginPromise;
              const retryRes = await request(options);
              resolve(retryRes);
            } catch (err) {
              wx.showModal({
                content: '操作失败，请先登录',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.removeStorageSync('token');
                    wx.switchTab({ url: '/pages/mine/mine' });
                  }
                },
              });
              resolve(res);
            }
            return;
          }

          wx.showModal({
            content: '操作失败，请先登录',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.removeStorageSync('token');
                wx.reLaunch({ url: '/pages/mine/mine' });
              }
            },
          });
          resolve(res);
          return;
        }
        resolve(res);
      },
      fail: (err) => {
        // 网络层失败（超时/域名不可达等），避免未捕获 Promise 触发 MiniProgramError 红屏
        console.warn('request fail:', options.url, err && err.errMsg);
        resolve({
          statusCode: 0,
          data: {
            code: 408,
            msg: (err && err.errMsg) || '网络请求失败',
          },
          errMsg: (err && err.errMsg) || 'request:fail',
        });
      },
    });
  });
}

export default request;
