import { getEnvValue, isDev } from '../config/env.js'

const API_BASE_URL = getEnvValue('API_BASE_URL')

/**
 * 请求拦截处理
 * 自动添加 token 到请求头
 */
const getHeaders = () => {
  const token = uni.getStorageSync('access_token')
  const headers = {
    'Content-Type': 'application/json'
  }
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }
  return headers
}

/**
 * 统一请求方法
 * @param {Object} options - 请求配置
 * @returns {Promise} 请求 Promise
 */
const request = (options) => {
  const debug = getEnvValue('DEBUG')
  const fullUrl = `${API_BASE_URL}${options.url}`

  // 请求日志
  if (debug) {
    console.log('[API Request]', {
      method: options.method || 'GET',
      url: fullUrl,
      path: options.url,
      env: import.meta.env.VITE_APP_ENV
    })
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: fullUrl,
      method: options.method || 'GET',
      data: options.data,
      header: getHeaders(),
      timeout: 30000,
      success: (res) => {
        const { data, statusCode } = res

        // 响应日志
        if (debug) {
          console.log('[API Response]', {
            path: options.url,
            status: statusCode,
            code: data?.code,
            success: data?.code === 200 || data?.code === 0
          })
        }

        // 处理 401 未授权
        if (statusCode === 401) {
          uni.removeStorageSync('access_token')
          uni.removeStorageSync('refresh_token')
          uni.redirectTo({ url: '/pages/login/index' })
          reject(new Error('登录已过期，请重新登录'))
          return
        }

        // 后端返回格式：{ code, message, data }
        if (data.code === 200 || data.code === 0) {
          resolve(data)
        } else {
          reject(new Error(data.message || '请求失败'))
        }
      },
      fail: (err) => {
        // 错误日志
        if (debug) {
          console.error('[API Error]', {
            path: options.url,
            error: err.errMsg,
            env: import.meta.env.VITE_APP_ENV
          })
        }
        reject(new Error(err.errMsg || '网络错误'))
      }
    })
  })
}

/**
 * GET 请求
 */
export const get = (url, params = {}) => {
  // 构建查询字符串
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
  const fullUrl = queryString ? `${url}?${queryString}` : url

  return request({ url: fullUrl, method: 'GET' })
}

/**
 * POST 请求
 */
export const post = (url, data = {}) => {
  return request({ url, method: 'POST', data })
}

/**
 * PUT 请求
 */
export const put = (url, data = {}) => {
  return request({ url, method: 'PUT', data })
}

/**
 * DELETE 请求
 */
export const del = (url, params = {}) => {
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
  const fullUrl = queryString ? `${url}?${queryString}` : url

  return request({ url: fullUrl, method: 'DELETE' })
}

export default {
  get,
  post,
  put,
  del
}
