import { ref } from 'vue'

const baseUrl = `${import.meta.env?.VITE_API_URL || ''}${import.meta.env?.VITE_API_PREFIX || '/api'}`

function getPlatform() {
  // #ifdef MP-WEIXIN
  return 'wxmini'
  // #endif
  // #ifdef H5
  return 'h5'
  // #endif
  return 'h5'
}

function request(path, options = {}) {
  const data = ref(null)
  const error = ref(null)
  const url = path.startsWith('http') ? path : `${baseUrl}${path.startsWith('/') ? path : '/' + path}`
  const separator = url.includes('?') ? '&' : '?'
  const finalUrl = `${url}${separator}t=${Date.now()}`

  const token = uni.getStorageSync?.('token') || ''
  const header = {
    'Content-Type': 'application/json',
    'X-Platform': getPlatform(),
    ...(token ? { Authorization: token } : {}),
    ...options.header,
  }

  const doRequest = () =>
    new Promise((resolve) => {
      uni.request({
        url: finalUrl,
        method: options.method || 'GET',
        data: options.body || options.data,
        header,
        success: (res) => {
          if (res.statusCode === 401) {
            // 清除 token，App.vue 会自动重新登录
            uni.removeStorageSync('token')
            uni.removeStorageSync('refreshAfter')
            uni.removeStorageSync('accessExpire')
            uni.removeStorageSync('userInfo')
            uni.removeStorageSync('agentInfo')
          }
          data.value = res.data
          error.value = res.statusCode >= 400 ? (res.data?.msg || '请求失败') : null
          resolve({ data, error })
        },
        fail: (err) => {
          error.value = err.errMsg || '网络错误'
          resolve({ data, error })
        },
      })
    })

  return {
    json: () => doRequest().then(() => ({ data, error })),
  }
}

export default function useApiFetch(path) {
  return {
    get() {
      return request(path, { method: 'GET' })
    },
    post(body) {
      return request(path, { method: 'POST', body })
    },
  }
}
