import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { 
  getAccessToken, 
  getRefreshToken, 
  setTokens, 
  clearTokens, 
  isTokenExpiringSoon
} from './auth'
import router from '@/router'

// API 响应结构
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 分页结果
export interface PagedResult<T> {
  list: T[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

// URLs that don't require authentication
const WHITE_LIST_URLS = ['/admin/auth/captcha', '/admin/auth/login', '/admin/auth/refresh']

// Token refresh state management
let isRefreshing = false
let refreshPromise: Promise<boolean> | null = null
let pendingRequests: Array<{
  config: InternalAxiosRequestConfig
  resolve: (value: any) => void
  reject: (reason?: any) => void
}> = []

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 30000
})

/**
 * Check if URL is in whitelist (doesn't require token)
 */
function isWhiteListUrl(url: string | undefined): boolean {
  if (!url) return false
  return WHITE_LIST_URLS.some(whiteUrl => url.includes(whiteUrl))
}

/**
 * Perform token refresh
 * @returns Promise that resolves to true if refresh succeeded, false otherwise
 */
async function doRefreshToken(): Promise<boolean> {
  const refreshTokenValue = getRefreshToken()
  if (!refreshTokenValue) {
    return false
  }

  try {
    // Import dynamically to avoid circular dependency
    const { refreshToken } = await import('@/api/auth')
    const response = await refreshToken(refreshTokenValue)
    
    if (response.code === 0 && response.data) {
      const { accessToken, refreshToken: newRefreshToken, expiresIn } = response.data
      setTokens(accessToken, newRefreshToken, expiresIn)
      return true
    }
    return false
  } catch (error) {
    console.error('Token refresh failed:', error)
    return false
  }
}

/**
 * Handle token refresh with concurrency control
 * Ensures only one refresh request is made at a time
 */
async function handleTokenRefresh(): Promise<boolean> {
  if (isRefreshing) {
    // Wait for the ongoing refresh to complete
    return refreshPromise!
  }

  isRefreshing = true
  refreshPromise = doRefreshToken()
  
  try {
    const success = await refreshPromise
    
    // Process pending requests
    if (success) {
      pendingRequests.forEach(({ config, resolve }) => {
        // Update token in the pending request
        config.headers['Authorization'] = `Bearer ${getAccessToken()}`
        resolve(service(config))
      })
    } else {
      pendingRequests.forEach(({ reject }) => {
        reject(new Error('Token refresh failed'))
      })
    }
    
    return success
  } finally {
    isRefreshing = false
    refreshPromise = null
    pendingRequests = []
  }
}

/**
 * Handle 401 error by attempting token refresh
 */
async function handle401Error(error: any): Promise<any> {
  const originalConfig = error.config as InternalAxiosRequestConfig & { _retry?: boolean }
  
  // Don't retry if already retried or if it's a refresh request
  if (originalConfig._retry || isWhiteListUrl(originalConfig.url)) {
    return Promise.reject(error)
  }

  const refreshTokenValue = getRefreshToken()
  if (!refreshTokenValue) {
    // No refresh token, redirect to login
    clearTokens()
    router.push('/login')
    return Promise.reject(error)
  }

  originalConfig._retry = true

  if (isRefreshing) {
    // Add to pending requests queue
    return new Promise((resolve, reject) => {
      pendingRequests.push({ config: originalConfig, resolve, reject })
    })
  }

  const success = await handleTokenRefresh()
  
  if (success) {
    // Retry the original request with new token
    originalConfig.headers['Authorization'] = `Bearer ${getAccessToken()}`
    return service(originalConfig)
  } else {
    // Refresh failed, redirect to login
    clearTokens()
    ElMessage.error('登录已过期，请重新登录')
    router.push('/login')
    return Promise.reject(error)
  }
}

// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    // Skip token handling for whitelist URLs
    if (isWhiteListUrl(config.url)) {
      return config
    }

    // Check if token is about to expire and proactively refresh
    if (isTokenExpiringSoon() && !isRefreshing) {
      const refreshTokenValue = getRefreshToken()
      if (refreshTokenValue) {
        await handleTokenRefresh()
      }
    }

    // Add token to request
    const token = getAccessToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const res = response.data
    
    // code 为 0 表示成功
    if (res.code === 0) {
      return res as any
    }
    
    // 处理业务错误
    ElMessage.error(res.message || '请求失败')
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  async (error) => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // Attempt token refresh for 401 errors
          return handle401Error(error)
        case 403:
          ElMessage.error('没有操作权限')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          // 优先显示后端返回的错误信息
          ElMessage.error(data?.message || '服务器内部错误')
          break
        default:
          ElMessage.error(data?.message || '请求失败')
      }
    } else {
      ElMessage.error('网络连接失败')
    }
    
    return Promise.reject(error)
  }
)

// 封装请求方法
export function request<T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
  return service(config)
}

export default service
