import axios, { isAxiosError } from 'axios';
import { hc } from 'hono/client'
import type {
  AuthRoutes, UserRoutes, RoleRoutes, FileRoutes,
  AdvertisementRoutes, AdvertisementTypeRoutes, GoodsCategoryRoutes, GoodsRoutes,
  SupplierRoutes, MerchantRoutes, 
  DeliveryAddressRoutes, OrderRoutes, OrderGoodsRoutes, OrderRefundRoutes, AdminAreaRoutes
} from '@d8d/server';

// 创建 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;
    })
  }

  const response = await axios.request({
    url: url.toString(),
    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
    }
  )
}

// 创建客户端
export const authClient = hc<AuthRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.auth

export const userClient = hc<UserRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.users

export const roleClient = hc<RoleRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.roles

export const fileClient = hc<FileRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.files

export const advertisementClient = hc<AdvertisementRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.advertisements

export const advertisementTypeClient = hc<AdvertisementTypeRoutes>('/', {
  fetch: axiosFetch,
}).api.v1['advertisement-types']

export const goodsCategoryClient = hc<GoodsCategoryRoutes>('/', {
  fetch: axiosFetch,
}).api.v1['goods-categories']

export const goodsClient = hc<GoodsRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.goods

export const supplierClient = hc<SupplierRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.suppliers

export const merchantClient = hc<MerchantRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.merchants

export const areaClient = hc<AdminAreaRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.admin.areas

export const deliveryAddressClient = hc<DeliveryAddressRoutes>('/', {
  fetch: axiosFetch,
}).api.v1['delivery-addresses']

// 订单相关客户端
export const orderClient = hc<OrderRoutes>('/', {
  fetch: axiosFetch,
}).api.v1.orders

export const orderGoodsClient = hc<OrderGoodsRoutes>('/', {
  fetch: axiosFetch,
}).api.v1['orders-goods']

export const orderRefundClient = hc<OrderRefundRoutes>('/', {
  fetch: axiosFetch,
}).api.v1['orders-refund']