const getAppInstance = () => getApp();
const config = require('../config/index');

const getDefaultBaseUrl = () => {
  const apiBaseUrl = String(config?.API_BASE_URL || '').replace(/\/+$/, '');
  if (!apiBaseUrl) return 'https://ai-c.maimanji.com';
  return apiBaseUrl.endsWith('/api') ? apiBaseUrl.slice(0, -4) : apiBaseUrl;
};

const getBaseUrl = () => {
  const app = getAppInstance();
  const fromGlobal = app?.globalData?.baseUrl;
  const fromStorage = wx.getStorageSync('baseUrl');
  if (config?.ENV === 'development') {
    const storageUrl = String(fromStorage || '').trim();
    const allowStorage =
      /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(storageUrl) ||
      /^https?:\/\/(0\.0\.0\.0)(:\d+)?$/i.test(storageUrl);
    return (allowStorage ? storageUrl : '') || fromGlobal || getDefaultBaseUrl();
  }
  return fromStorage || fromGlobal || getDefaultBaseUrl();
};

const getToken = () => wx.getStorageSync('auth_token') || '';

const request = ({ url, method = 'GET', data, header = {} }) => {
  return new Promise((resolve, reject) => {
    const baseUrl = getBaseUrl();
    wx.request({
      url: `${baseUrl}${url}`,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        ...(getToken() ? { Authorization: `Bearer ${getToken()}` } : {}),
        ...header
      },
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        const errMsg = err?.errMsg || '';
        const isConnRefused = /ERR_CONNECTION_REFUSED/i.test(errMsg);
        const isRequestFail = /^request:fail/i.test(errMsg);
        const userMessage = isConnRefused || isRequestFail
          ? `网络连接失败：无法连接到 ${baseUrl}，请确认后端服务已启动且接口地址正确`
          : '网络请求失败';
        reject({ ...err, baseUrl, userMessage });
      }
    });
  });
};

module.exports = {
  request,
  getBaseUrl
};
