import axios, { isAxiosError } from 'axios';
import { hc } from 'hono/client'
import type { Hono } from 'hono'

// 创建 axios 适配器
const axiosFetch = async (url: RequestInfo | URL, init?: RequestInit) => {
  const requestHeaders: Record<string, string> = {};

  if (init?.headers instanceof Headers) {
    init.headers.forEach((value, key) => {
      requestHeaders[key] = value;
    })
  }

  // 处理URL中的多余斜杠
  let requestUrl = url.toString()
  // 替换连续的斜杠为单个斜杠，但保留协议后的双斜杠
  requestUrl = requestUrl.replace(/([^:])\/\/+/g, '$1/')
  // 处理路径末尾的斜杠和查询参数前的斜杠
  requestUrl = requestUrl.replace(/\/\?/g, '?')

  const response = await axios.request({
    url: requestUrl,
    method: init?.method || 'GET',
    headers: requestHeaders,
    data: init?.body,
  }).catch((error) => {
    console.log('axiosFetch error', error)

    if (isAxiosError(error)) {
      return {
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data,
        headers: error.response?.headers
      }
    }
    throw error;
  })

  const responseHeaders = new Headers();
  if (response.headers) {
    for (const [key, value] of Object.entries(response.headers)) {
      responseHeaders.set(key, value);
    }
  }


  // 处理204 No Content响应，不设置body
  const body = response.status === 204
    ? null
    : responseHeaders.get('content-type')?.includes('application/json')
      ? JSON.stringify(response.data)
      : response.data;

  return new Response(
    body,
    {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders
    }
  )
}

// 创建Hono RPC客户端
export const rpcClient = <T extends Hono<any, any, any>>(aptBaseUrl: string): ReturnType<typeof hc<T>> => {
  return hc<T>(aptBaseUrl, {
    fetch: axiosFetch
  })
}