import { apiClient } from './client';
import type { TradeRecord } from '../types/models';

export interface GetTradesParams {
  limit?: number;
  agentId?: string;
  startDate?: string;
  endDate?: string;
}

export async function getTrades(params?: GetTradesParams): Promise<TradeRecord[]> {
  const response = await apiClient.get<any[]>('/api/trades', {
    params,
  });
  
  // Map backend response fields to frontend TradeRecord interface
  return response.data.map(trade => ({
    id: trade.trade_id || trade.id || String(Math.random()),
    agentId: trade.agent_id || trade.agentId || 'Unknown',
    agentName: trade.agent_name || trade.agent_id || trade.agentId || 'Unknown',
    symbol: trade.symbol || 'N/A',
    side: trade.side || 'buy',
    quantity: trade.amount || trade.quantity || 0,
    price: trade.price || 0,
    total: trade.value || trade.total || (trade.price * (trade.amount || trade.quantity || 0)),
    timestamp: trade.timestamp || new Date().toISOString(),
    pnl: trade.pnl,
    pnlPercent: trade.pnl_percent || trade.pnlPercent
  }));
}

export async function getRecentTrades(limit: number = 10): Promise<TradeRecord[]> {
  return getTrades({ limit });
}
