const app = getApp()

function getOrigin(url) {
  if (!url) return ''
  const match = url.match(/^(https?:\/\/[^/]+)/)
  return match ? match[1] : ''
}

function replaceUrl(data, targetOrigin) {
  if (!data || !targetOrigin) return data
  
  if (typeof data === 'string') {
    // Replace localhost/127.0.0.1 with target origin
    // Handle both http and https, though localhost usually http
    return data.replace(/https?:\/\/(localhost|127\.0\.0\.1):8000/g, targetOrigin)
  }
  
  if (Array.isArray(data)) {
    return data.map(item => replaceUrl(item, targetOrigin))
  }
  
  if (typeof data === 'object') {
    const newData = {}
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        newData[key] = replaceUrl(data[key], targetOrigin)
      }
    }
    return newData
  }
  
  return data
}

function unwrap(data) {
  // First, apply URL replacement if needed
  // We need to access app.globalData which might not be ready if called too early, 
  // but usually request is called after app launch.
  // Safely get app instance again inside function
  try {
      const app = getApp()
      if (app && app.globalData && app.globalData.baseUrl) {
          const origin = getOrigin(app.globalData.baseUrl)
          if (origin) {
              data = replaceUrl(data, origin)
          }
      }
  } catch (e) {
      console.warn('URL replacement failed', e)
  }

  if (data && typeof data === 'object' && 'code' in data && 'data' in data) {
    return data.data
  }
  return data
}

function request({ url, method = 'GET', data = {}, header = {} }) {
  return new Promise((resolve, reject) => {
    const app = getApp()
    if (app.globalData.token) {
        header['Authorization'] = `Bearer ${app.globalData.token}`
    }
    wx.request({
      url: `${app.globalData.baseUrl}${url.startsWith('/') ? '' : '/'}${url}`,
      method,
      data,
      header,
      success: (res) => {
        // Check HTTP status code
        if (res.statusCode >= 200 && res.statusCode < 300) {
             // Check logical code from backend wrapper
             if (res.data && typeof res.data === 'object' && 'code' in res.data) {
                 if (res.data.code < 200 || res.data.code >= 300) {
                     reject(res.data)
                     return
                 }
             }
             resolve(unwrap(res.data))
        } else {
             reject(res)
        }
      },
      fail: (err) => reject(err)
    })
  })
}

module.exports = { request }
