// Portfolio Persistence API Service
// Add this to your App.tsx or create a separate service file

import axios from 'axios'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8001'

export interface TradeRequest {
  action: 'BUY' | 'SELL'
  quantity: number
  price: number
  symbol?: string
  notes?: string
  stop_loss?: number
  take_profit?: number
}

export interface TradeResponse {
  trade: {
    id: number
    action: string
    quantity: number
    price: number
    total: number
    pnl: number | null
    timestamp: number
  }
  portfolio: {
    cash: number
    initial_capital: number
    position: {
      symbol: string
      quantity: number
      avg_price: number
      current_price: number
      unrealized_pnl: number
      unrealized_pnl_percent: number
    } | null
    trades: Array<{
      id: number
      action: string
      quantity: number
      price: number
      total: number
      pnl: number | null
      timestamp: number
    }>
    equity_history: Array<{
      time: number
      equity: number
    }>
    total_pnl: number
    total_pnl_percent: number
  }
}

export interface PortfolioState {
  cash: number
  initial_capital: number
  position: {
    symbol: string
    quantity: number
    avg_price: number
    current_price: number
    unrealized_pnl: number
    unrealized_pnl_percent: number
  } | null
  trades: Array<{
    id: number
    action: string
    quantity: number
    price: number
    total: number
    pnl: number | null
    timestamp: number
  }>
  equity_history: Array<{
    time: number
    equity: number
  }>
  total_pnl: number
  total_pnl_percent: number
}

export interface TradingStats {
  total_trades: number
  winning_trades: number
  losing_trades: number
  win_rate: number
  total_pnl: number
  total_pnl_percent: number
  total_profit: number
  total_loss: number
  profit_factor: number
  current_capital: number
  initial_capital: number
}

// API functions

export async function executeTradeAPI(trade: TradeRequest): Promise<TradeResponse> {
  const response = await axios.post(`${API_URL}/api/trading/execute`, trade)
  return response.data
}

export async function getPortfolioAPI(): Promise<PortfolioState> {
  const response = await axios.get(`${API_URL}/api/trading/portfolio`)
  return response.data
}

export async function resetSimulationAPI(): Promise<{ message: string; portfolio: PortfolioState }> {
  const response = await axios.post(`${API_URL}/api/trading/reset`)
  return response.data
}

export async function getTradeHistoryAPI(limit = 100): Promise<Array<any>> {
  const response = await axios.get(`${API_URL}/api/trading/history`, {
    params: { limit }
  })
  return response.data
}

export async function getTradingStatsAPI(): Promise<TradingStats> {
  const response = await axios.get(`${API_URL}/api/trading/stats`)
  return response.data
}

// Utility to convert backend portfolio to frontend Portfolio type
export function convertBackendPortfolio(backendPortfolio: PortfolioState, currentPrice: number) {
  return {
    cash: backendPortfolio.cash,
    initialCapital: backendPortfolio.initial_capital,
    totalValue: backendPortfolio.cash + (backendPortfolio.position?.quantity || 0) * currentPrice,
    totalPnl: backendPortfolio.total_pnl,
    totalPnlPercent: backendPortfolio.total_pnl_percent,
    position: backendPortfolio.position ? {
      symbol: backendPortfolio.position.symbol,
      quantity: backendPortfolio.position.quantity,
      avgPrice: backendPortfolio.position.avg_price,
      currentPrice: backendPortfolio.position.current_price,
      unrealizedPnl: backendPortfolio.position.unrealized_pnl,
      unrealizedPnlPercent: backendPortfolio.position.unrealized_pnl_percent
    } : null,
    trades: backendPortfolio.trades.map(t => ({
      id: t.id.toString(),
      timestamp: t.timestamp * 1000, // Convert to milliseconds
      action: t.action as 'BUY' | 'SELL',
      quantity: t.quantity,
      price: t.price,
      total: t.total,
      pnl: t.pnl || undefined
    }))
  }
}
