/**
 * 带有重试机制的API请求函数
 * @param url 请求URL
 * @param options 请求选项
 * @param retries 重试次数
 * @param retryDelay 重试延迟(ms)
 * @returns Promise<Response>
 */
export async function fetchWithRetry(
  url: string,
  options: RequestInit = {},
  retries = 3,
  retryDelay = 1000,
): Promise<Response> {
  try {
    const response = await fetch(url, options)

    if (!response.ok && retries > 0) {
      console.log(`请求失败，${retryDelay}ms后重试，剩余重试次数: ${retries - 1}`)
      await new Promise((resolve) => setTimeout(resolve, retryDelay))
      return fetchWithRetry(url, options, retries - 1, retryDelay * 2)
    }

    return response
  } catch (error) {
    if (retries > 0) {
      console.log(`请求出错，${retryDelay}ms后重试，剩余重试次数: ${retries - 1}`)
      await new Promise((resolve) => setTimeout(resolve, retryDelay))
      return fetchWithRetry(url, options, retries - 1, retryDelay * 2)
    }
    throw error
  }
}

/**
 * 处理API响应的通用函数
 * @param response 响应对象
 * @returns Promise<T>
 */
export async function handleApiResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}))
    throw new Error(errorData.message || `请求失败: ${response.status}`)
  }

  return response.json()
}
