/**
 * Pacifica交易操作客户端
 *
 * 负责处理Pacifica DEX的所有交易操作接口
 * 包括订单创建、限价单、市价单、取消订单、批量操作等
 */

import { HttpClientRequest, HttpClientResponse } from '@/types/httpClient'
import {
  PacificaOrderRequest,
  PacificaOrder,
  PacificaOrderResponse,
  PacificaCancelOrderRequest,
  PacificaCancelOrderResponse,
  PacificaBatchOrderRequest,
  PacificaBatchOrderResponse,
  PacificaAccountInfo,
  PacificaFuturesAccountInfo,
  PacificaBalance,
  PacificaPosition,
  PacificaOrderQueryParams,
  PacificaOrderHistoryParams,
  PacificaTradeHistoryParams,
  PacificaApiResponse,
  PacificaListResponse,
  PacificaFill,
} from '@/types/pacifica'
import { UniversalHttpClient } from '@/utils/universalHttpClient'

export class PacificaTradingClient {
  private httpClient: UniversalHttpClient
  private accountId: string
  private recvWindow: number = 5000

  constructor(httpClient: UniversalHttpClient, accountId: string) {
    this.httpClient = httpClient
    this.accountId = accountId
  }

  // ======================== 订单操作接口 ========================

  /**
   * 创建新订单
   */
  async createOrder(orderRequest: PacificaOrderRequest): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const body = {
      ...orderRequest,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'POST',
      url: '/api/v3/order',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<PacificaOrderResponse>(request)
    return this.wrapResponse(response)
  }

  /**
   * 创建限价买单
   */
  async createLimitBuyOrder(
    symbol: string,
    quantity: string,
    price: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side: 'BUY',
      type: 'LIMIT',
      timeInForce: 'GTC',
      quantity,
      price,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建限价卖单
   */
  async createLimitSellOrder(
    symbol: string,
    quantity: string,
    price: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side: 'SELL',
      type: 'LIMIT',
      timeInForce: 'GTC',
      quantity,
      price,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建市价买单
   */
  async createMarketBuyOrder(
    symbol: string,
    quantity?: string,
    quoteOrderQty?: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side: 'BUY',
      type: 'MARKET',
      quantity,
      quoteOrderQty,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建市价卖单
   */
  async createMarketSellOrder(
    symbol: string,
    quantity: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side: 'SELL',
      type: 'MARKET',
      quantity,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建止损单
   */
  async createStopLossOrder(
    symbol: string,
    side: 'BUY' | 'SELL',
    quantity: string,
    stopPrice: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side,
      type: 'STOP_LOSS',
      quantity,
      stopPrice,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建止损限价单
   */
  async createStopLossLimitOrder(
    symbol: string,
    side: 'BUY' | 'SELL',
    quantity: string,
    price: string,
    stopPrice: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side,
      type: 'STOP_LOSS_LIMIT',
      timeInForce: 'GTC',
      quantity,
      price,
      stopPrice,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建获利单
   */
  async createTakeProfitOrder(
    symbol: string,
    side: 'BUY' | 'SELL',
    quantity: string,
    stopPrice: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side,
      type: 'TAKE_PROFIT',
      quantity,
      stopPrice,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  /**
   * 创建获利限价单
   */
  async createTakeProfitLimitOrder(
    symbol: string,
    side: 'BUY' | 'SELL',
    quantity: string,
    price: string,
    stopPrice: string,
    options?: Partial<PacificaOrderRequest>,
  ): Promise<PacificaApiResponse<PacificaOrderResponse>> {
    const orderRequest: PacificaOrderRequest = {
      symbol,
      side,
      type: 'TAKE_PROFIT_LIMIT',
      timeInForce: 'GTC',
      quantity,
      price,
      stopPrice,
      ...options,
    }

    return this.createOrder(orderRequest)
  }

  // ======================== 订单查询接口 ========================

  /**
   * 查询订单状态
   */
  async getOrder(params: PacificaOrderQueryParams): Promise<PacificaApiResponse<PacificaOrder>> {
    const queryParams = new URLSearchParams()
    queryParams.append('symbol', params.symbol)

    if (params.orderId) queryParams.append('orderId', params.orderId.toString())
    if (params.origClientOrderId) queryParams.append('origClientOrderId', params.origClientOrderId)

    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', (params.recvWindow || this.recvWindow).toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/api/v3/order?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<PacificaOrder>(request)
    return this.wrapResponse(response)
  }

  /**
   * 获取当前开放订单
   */
  async getOpenOrders(symbol?: string): Promise<PacificaApiResponse<PacificaOrder[]>> {
    const queryParams = new URLSearchParams()
    if (symbol) queryParams.append('symbol', symbol)

    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', this.recvWindow.toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/api/v3/openOrders?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<PacificaOrder[]>(request)
    return this.wrapResponse(response)
  }

  /**
   * 获取所有订单历史
   */
  async getAllOrders(params: PacificaOrderHistoryParams): Promise<PacificaApiResponse<PacificaOrder[]>> {
    const queryParams = new URLSearchParams()
    queryParams.append('symbol', params.symbol)

    if (params.orderId) queryParams.append('orderId', params.orderId.toString())
    if (params.startTime) queryParams.append('startTime', params.startTime.toString())
    if (params.endTime) queryParams.append('endTime', params.endTime.toString())
    if (params.limit) queryParams.append('limit', params.limit.toString())

    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', (params.recvWindow || this.recvWindow).toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/api/v3/allOrders?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<PacificaOrder[]>(request)
    return this.wrapResponse(response)
  }

  // ======================== 订单取消接口 ========================

  /**
   * 取消订单
   */
  async cancelOrder(params: PacificaCancelOrderRequest): Promise<PacificaApiResponse<PacificaCancelOrderResponse>> {
    const body = {
      ...params,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'DELETE',
      url: '/api/v3/order',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<PacificaCancelOrderResponse>(request)
    return this.wrapResponse(response)
  }

  /**
   * 取消指定交易对的所有开放订单
   */
  async cancelAllOrders(symbol: string): Promise<PacificaApiResponse<PacificaCancelOrderResponse[]>> {
    const body = {
      symbol,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'DELETE',
      url: '/api/v3/openOrders',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<PacificaCancelOrderResponse[]>(request)
    return this.wrapResponse(response)
  }

  /**
   * 取消订单并创建新订单 (OCO)
   */
  async cancelAndReplaceOrder(
    cancelParams: PacificaCancelOrderRequest,
    newOrderParams: PacificaOrderRequest,
  ): Promise<
    PacificaApiResponse<{
      cancelResult: 'SUCCESS' | 'FAILURE'
      newOrderResult: 'SUCCESS' | 'FAILURE' | 'NOT_ATTEMPTED'
      cancelResponse?: PacificaCancelOrderResponse
      newOrderResponse?: PacificaOrderResponse
    }>
  > {
    const body = {
      ...cancelParams,
      ...newOrderParams,
      cancelReplaceMode: 'STOP_ON_FAILURE',
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'POST',
      url: '/api/v3/order/cancelReplace',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<any>(request)
    return this.wrapResponse(response)
  }

  // ======================== 批量操作接口 ========================

  /**
   * 批量创建订单
   */
  async createBatchOrders(orders: PacificaOrderRequest[]): Promise<PacificaApiResponse<PacificaBatchOrderResponse>> {
    const batchOrders = orders.map(order => ({
      ...order,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }))

    const body = {
      batchOrders: JSON.stringify(batchOrders),
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'POST',
      url: '/api/v3/batchOrders',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<PacificaBatchOrderResponse>(request)
    return this.wrapResponse(response)
  }

  /**
   * 批量取消订单
   */
  async cancelBatchOrders(
    symbol: string,
    orderIds?: number[],
    origClientOrderIds?: string[],
  ): Promise<PacificaApiResponse<PacificaCancelOrderResponse[]>> {
    const body: any = {
      symbol,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }

    if (orderIds && orderIds.length > 0) {
      body.orderIdList = JSON.stringify(orderIds)
    }

    if (origClientOrderIds && origClientOrderIds.length > 0) {
      body.origClientOrderIdList = JSON.stringify(origClientOrderIds)
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'DELETE',
      url: '/api/v3/batchOrders',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<PacificaCancelOrderResponse[]>(request)
    return this.wrapResponse(response)
  }

  // ======================== 账户信息接口 ========================

  /**
   * 获取账户信息
   */
  async getAccountInfo(): Promise<PacificaApiResponse<PacificaAccountInfo>> {
    const queryParams = new URLSearchParams()
    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', this.recvWindow.toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/api/v3/account?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<PacificaAccountInfo>(request)
    return this.wrapResponse(response)
  }

  /**
   * 获取期货账户信息
   */
  async getFuturesAccountInfo(): Promise<PacificaApiResponse<PacificaFuturesAccountInfo>> {
    const queryParams = new URLSearchParams()
    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', this.recvWindow.toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/fapi/v2/account?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<PacificaFuturesAccountInfo>(request)
    return this.wrapResponse(response)
  }

  /**
   * 获取交易历史
   */
  async getTradeHistory(params: PacificaTradeHistoryParams): Promise<PacificaApiResponse<PacificaFill[]>> {
    const queryParams = new URLSearchParams()
    queryParams.append('symbol', params.symbol)

    if (params.startTime) queryParams.append('startTime', params.startTime.toString())
    if (params.endTime) queryParams.append('endTime', params.endTime.toString())
    if (params.fromId) queryParams.append('fromId', params.fromId.toString())
    if (params.limit) queryParams.append('limit', params.limit.toString())

    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', (params.recvWindow || this.recvWindow).toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/api/v3/myTrades?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<PacificaFill[]>(request)
    return this.wrapResponse(response)
  }

  // ======================== 高级交易功能 ========================

  /**
   * 创建 OCO 订单 (One-Cancels-Other)
   */
  async createOCOOrder(
    symbol: string,
    side: 'BUY' | 'SELL',
    quantity: string,
    price: string,
    stopPrice: string,
    stopLimitPrice?: string,
    options?: {
      listClientOrderId?: string
      limitClientOrderId?: string
      stopClientOrderId?: string
      limitIcebergQty?: string
      stopIcebergQty?: string
      stopLimitTimeInForce?: 'GTC' | 'FOK' | 'IOC'
      newOrderRespType?: 'ACK' | 'RESULT' | 'FULL'
    },
  ): Promise<PacificaApiResponse<any>> {
    const body = {
      symbol,
      side,
      quantity,
      price,
      stopPrice,
      stopLimitPrice,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
      ...options,
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'POST',
      url: '/api/v3/order/oco',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<any>(request)
    return this.wrapResponse(response)
  }

  /**
   * 查询 OCO 订单
   */
  async getOCOOrder(orderListId?: number, origClientOrderId?: string): Promise<PacificaApiResponse<any>> {
    const queryParams = new URLSearchParams()

    if (orderListId) queryParams.append('orderListId', orderListId.toString())
    if (origClientOrderId) queryParams.append('origClientOrderId', origClientOrderId)

    queryParams.append('timestamp', Date.now().toString())
    queryParams.append('recvWindow', this.recvWindow.toString())

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'GET',
      url: `/api/v3/orderList?${queryParams.toString()}`,
      headers: {
        'Content-Type': 'application/json',
      },
    }

    const response = await this.httpClient.request<any>(request)
    return this.wrapResponse(response)
  }

  /**
   * 取消 OCO 订单
   */
  async cancelOCOOrder(
    symbol: string,
    orderListId?: number,
    listClientOrderId?: string,
    newClientOrderId?: string,
  ): Promise<PacificaApiResponse<any>> {
    const body = {
      symbol,
      orderListId,
      listClientOrderId,
      newClientOrderId,
      timestamp: Date.now(),
      recvWindow: this.recvWindow,
    }

    const request: HttpClientRequest = {
      platform: 'pacifica',
      accountId: this.accountId,
      method: 'DELETE',
      url: '/api/v3/orderList',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    }

    const response = await this.httpClient.request<any>(request)
    return this.wrapResponse(response)
  }

  // ======================== 配置管理 ========================

  /**
   * 设置接收窗口时间
   */
  setRecvWindow(recvWindow: number): void {
    this.recvWindow = recvWindow
  }

  /**
   * 获取接收窗口时间
   */
  getRecvWindow(): number {
    return this.recvWindow
  }

  // ======================== 辅助方法 ========================

  /**
   * 包装响应数据为统一格式
   */
  private wrapResponse<T>(response: HttpClientResponse<T>): PacificaApiResponse<T> {
    return {
      data: response.data,
      success: response.status >= 200 && response.status < 300,
      code: response.status,
      message: response.statusText,
      timestamp: Date.now(),
    }
  }

  /**
   * 验证订单参数
   */
  private validateOrderRequest(orderRequest: PacificaOrderRequest): boolean {
    // 基础验证
    if (!orderRequest.symbol || !orderRequest.side || !orderRequest.type) {
      return false
    }

    // 限价单必须有价格
    if (orderRequest.type === 'LIMIT' && !orderRequest.price) {
      return false
    }

    // 市价单必须有数量或金额
    if (orderRequest.type === 'MARKET' && !orderRequest.quantity && !orderRequest.quoteOrderQty) {
      return false
    }

    return true
  }

  /**
   * 格式化订单参数
   */
  private formatOrderRequest(orderRequest: PacificaOrderRequest): PacificaOrderRequest {
    return {
      ...orderRequest,
      symbol: orderRequest.symbol.toUpperCase(),
      side: orderRequest.side.toUpperCase() as 'BUY' | 'SELL',
      type: orderRequest.type.toUpperCase() as any,
    }
  }

  /**
   * 获取客户端配置
   */
  getClientConfig() {
    return {
      accountId: this.accountId,
      platform: 'pacifica',
      recvWindow: this.recvWindow,
      endpoints: {
        order: '/api/v3/order',
        openOrders: '/api/v3/openOrders',
        allOrders: '/api/v3/allOrders',
        account: '/api/v3/account',
        myTrades: '/api/v3/myTrades',
        batchOrders: '/api/v3/batchOrders',
        oco: '/api/v3/order/oco',
      },
    }
  }
}
