import { apiClient } from './client'
import { OrderCreate, OrderResponse, PositionResponse } from '../types'

export const tradingApi = {
  createOrder: async (order: OrderCreate): Promise<OrderResponse> => {
    const response = await apiClient.post('/api/trading/orders', order)
    return response.data
  },

  getOrders: async (paperTrading: boolean = true, limit: number = 100): Promise<OrderResponse[]> => {
    const response = await apiClient.get('/api/trading/orders', {
      params: { paper_trading: paperTrading, limit },
    })
    return response.data
  },

  getOrder: async (orderId: number): Promise<OrderResponse> => {
    const response = await apiClient.get(`/api/trading/orders/${orderId}`)
    return response.data
  },

  cancelOrder: async (orderId: number): Promise<void> => {
    await apiClient.post(`/api/trading/orders/${orderId}/cancel`)
  },

  cancelAllOrders: async (paperTrading: boolean = true): Promise<{
    status: string
    cancelled_count: number
    failed_count: number
    total_orders: number
  }> => {
    const response = await apiClient.post('/api/trading/orders/cancel-all', null, {
      params: { paper_trading: paperTrading },
    })
    return response.data
  },

  getPositions: async (paperTrading: boolean = true): Promise<PositionResponse[]> => {
    const response = await apiClient.get('/api/trading/positions', {
      params: { paper_trading: paperTrading },
    })
    return response.data
  },

  getBalance: async (paperTrading: boolean = true) => {
    const response = await apiClient.get('/api/trading/balance', {
      params: { paper_trading: paperTrading },
    })
    return response.data
  },
}
