import { adminOrderRoutes, adminOrderItemsRoutes, adminRefundsRoutes } from '@d8d/orders-module';
import { rpcClient } from '@d8d/shared-ui-components/utils/hc'

class OrderClientManager {
  private static instance: OrderClientManager;
  private adminOrderClient: ReturnType<typeof rpcClient<typeof adminOrderRoutes>> | null = null;
  private adminOrderItemsClient: ReturnType<typeof rpcClient<typeof adminOrderItemsRoutes>> | null = null;
  private adminRefundsClient: ReturnType<typeof rpcClient<typeof adminRefundsRoutes>> | null = null;

  private constructor() {}

  public static getInstance(): OrderClientManager {
    if (!OrderClientManager.instance) {
      OrderClientManager.instance = new OrderClientManager();
    }
    return OrderClientManager.instance;
  }

  // 初始化管理员订单客户端
  public initAdminOrderClient(baseUrl: string = '/'): ReturnType<typeof rpcClient<typeof adminOrderRoutes>> {
    return this.adminOrderClient = rpcClient<typeof adminOrderRoutes>(baseUrl);
  }

  // 初始化管理员订单商品客户端
  public initAdminOrderItemsClient(baseUrl: string = '/'): ReturnType<typeof rpcClient<typeof adminOrderItemsRoutes>> {
    return this.adminOrderItemsClient = rpcClient<typeof adminOrderItemsRoutes>(baseUrl);
  }

  // 初始化管理员退款客户端
  public initAdminRefundsClient(baseUrl: string = '/'): ReturnType<typeof rpcClient<typeof adminRefundsRoutes>> {
    return this.adminRefundsClient = rpcClient<typeof adminRefundsRoutes>(baseUrl);
  }

  // 获取管理员订单客户端实例
  public getAdminOrderClient(): ReturnType<typeof rpcClient<typeof adminOrderRoutes>> {
    if (!this.adminOrderClient) {
      return this.initAdminOrderClient()
    }
    return this.adminOrderClient;
  }

  // 获取管理员订单商品客户端实例
  public getAdminOrderItemsClient(): ReturnType<typeof rpcClient<typeof adminOrderItemsRoutes>> {
    if (!this.adminOrderItemsClient) {
      return this.initAdminOrderItemsClient()
    }
    return this.adminOrderItemsClient;
  }

  // 获取管理员退款客户端实例
  public getAdminRefundsClient(): ReturnType<typeof rpcClient<typeof adminRefundsRoutes>> {
    if (!this.adminRefundsClient) {
      return this.initAdminRefundsClient()
    }
    return this.adminRefundsClient;
  }

  // 重置所有客户端（用于测试或重新初始化）
  public reset(): void {
    this.adminOrderClient = null;
    this.adminOrderItemsClient = null;
    this.adminRefundsClient = null;
  }
}

// 导出单例实例
const orderClientManager = OrderClientManager.getInstance();

// 导出默认客户端实例（延迟初始化）
export const adminOrderClient = orderClientManager.getAdminOrderClient()
export const adminOrderItemsClient = orderClientManager.getAdminOrderItemsClient()
export const adminRefundsClient = orderClientManager.getAdminRefundsClient()

export {
  orderClientManager
}