import axios, {AxiosError, AxiosInstance} from 'axios'

// API 基础配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8888'

// 创建 axios 实例
const apiClient: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器 - 添加 Token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一错误处理
apiClient.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error: AxiosError<any>) => {
    if (error.response) {
      const { status, data } = error.response

      // Token 过期，尝试刷新
      if (status === 401 && data?.data?.reload) {
        const refreshToken = localStorage.getItem('refreshToken')
        if (refreshToken) {
          try {
            const response = await axios.post(`${API_BASE_URL}/app/auth/refresh`, {
              refreshToken,
            })
            const { token, refreshToken: newRefreshToken } = response.data.data
            localStorage.setItem('token', token)
            localStorage.setItem('refreshToken', newRefreshToken)

            // 重试原请求
            if (error.config) {
              error.config.headers.Authorization = `Bearer ${token}`
              return apiClient.request(error.config)
            }
          } catch (refreshError) {
            // 刷新失败，清除 Token 并跳转登录
            localStorage.removeItem('token')
            localStorage.removeItem('refreshToken')
            window.location.href = '/login'
            return Promise.reject(refreshError)
          }
        } else {
          // 没有 refreshToken，跳转登录
          window.location.href = '/login'
        }
      }

      // 返回错误信息
      return Promise.reject(data?.msg || '请求失败')
    }

    return Promise.reject(error.message || '网络错误')
  }
)

export default apiClient
