import Taro from '@tarojs/taro'
import type { Hono } from 'hono'
import { hc } from 'hono/client'
import ResponsePolyfill from './response-polyfill'

// API配置
const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'

// 完整的API地址
// const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`

// 创建自定义fetch函数，适配Taro.request
const taroFetch: any = async (input, init) => {
  const url = typeof input === 'string' ? input : input.url
  const method = init.method || 'GET'
  
  const requestHeaders: Record<string, string> = init.headers;

  const keyOfContentType = Object.keys(requestHeaders).find(item => item.toLowerCase() === 'content-type')
  if (!keyOfContentType) {
    requestHeaders['content-type'] = 'application/json'
  }

  // 构建Taro请求选项
  const options: Taro.request.Option = {
    url,
    method: method as any,
    data: init.body,
    header: requestHeaders
  }

  // 添加token
  const token = Taro.getStorageSync('mini_token')
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    }
  }

  try {
    // const response = await Taro.request(options)
    console.log('options', options)
    const response = await Taro.request(options)

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

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

    return new ResponsePolyfill(
      body,
      {
        status: response.statusCode,
        statusText: response.errMsg || 'OK',
        headers: responseHeaders
      }
    )
  } catch (error) {
    console.error('API Error:', error)
    Taro.showToast({
      title: error.message || '网络错误',
      icon: 'none'
    })
    throw error
  }
}

// 创建Hono RPC客户端
export const rpcClient = <T extends Hono>() => {
  return hc<T>(`${API_BASE_URL}`, {
    fetch: taroFetch
  })
}