import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Flag to prevent multiple refresh attempts
let isRefreshing = false
let failedQueue = []

const processQueue = (error, token = null) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error)
    } else {
      prom.resolve(token)
    }
  })
  failedQueue = []
}

// Request interceptor
api.interceptors.request.use(
  (config) => {
    // 添加调试日志
    console.log('🚀 API Request:', config.method.toUpperCase(), config.url, config.params || config.data)
    
    const token = localStorage.getItem('admin_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      console.log('🔑 Token:', token.substring(0, 20) + '...')
    } else {
      console.warn('⚠️ No token found in localStorage')
    }
    return config
  },
  (error) => {
    console.error('❌ Request Error:', error)
    return Promise.reject(error)
  }
)

// Response interceptor
api.interceptors.response.use(
  (response) => {
    // 添加调试日志
    console.log('✅ API Response:', response.config.url, response.status, response.data)
    return response
  },
  async (error) => {
    console.error('❌ API Error:', error.config?.url, error.response?.status, error.response?.data || error.message)
    const originalRequest = error.config
    const { response } = error
    
    if (response) {
      // Handle 401 with token refresh
      if (response.status === 401 && !originalRequest._retry) {
        // Don't retry refresh token requests
        if (originalRequest.url?.includes('/refresh-token')) {
          clearAuthData()
          router.push('/login')
          ElMessage.error('登录已过期，请重新登录')
          return Promise.reject(error)
        }

        if (isRefreshing) {
          // Queue the request while refreshing
          return new Promise((resolve, reject) => {
            failedQueue.push({ resolve, reject })
          }).then(token => {
            originalRequest.headers.Authorization = `Bearer ${token}`
            return api(originalRequest)
          }).catch(err => {
            return Promise.reject(err)
          })
        }

        originalRequest._retry = true
        isRefreshing = true

        const refreshToken = localStorage.getItem('admin_refresh_token')
        
        if (refreshToken) {
          try {
            const refreshResponse = await api.post('/api/v1/admin/refresh-token', {
              refreshToken
            })
            
            if (refreshResponse.data.success) {
              const { token: newToken, refreshToken: newRefreshToken } = refreshResponse.data.data
              
              localStorage.setItem('admin_token', newToken)
              if (newRefreshToken) {
                localStorage.setItem('admin_refresh_token', newRefreshToken)
              }
              
              // Update token expiry
              try {
                const payload = JSON.parse(atob(newToken.split('.')[1]))
                localStorage.setItem('admin_token_expiry', (payload.exp * 1000).toString())
              } catch {}
              
              api.defaults.headers.common.Authorization = `Bearer ${newToken}`
              originalRequest.headers.Authorization = `Bearer ${newToken}`
              
              processQueue(null, newToken)
              isRefreshing = false
              
              return api(originalRequest)
            }
          } catch (refreshError) {
            processQueue(refreshError, null)
            isRefreshing = false
            clearAuthData()
            router.push('/login')
            ElMessage.error('登录已过期，请重新登录')
            return Promise.reject(refreshError)
          }
        }
        
        // No refresh token available
        isRefreshing = false
        clearAuthData()
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
        return Promise.reject(error)
      }
      
      switch (response.status) {
        case 400:
          // 400错误不在这里显示，让调用方处理
          break
        case 403:
          ElMessage.error('没有权限执行此操作')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器错误，请稍后重试')
          break
        default:
          ElMessage.error(response.data?.error?.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  }
)

// Helper function to clear auth data
function clearAuthData() {
  localStorage.removeItem('admin_token')
  localStorage.removeItem('admin_refresh_token')
  localStorage.removeItem('admin_info')
  localStorage.removeItem('admin_token_expiry')
}

export default api
