import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export async function GET() {
  try {
    // Get the latest automation session
    const session = await prisma.automationSession.findFirst({
      orderBy: { createdAt: 'desc' }
    })

    // Get recent trades for calculations
    const recentTrades = session ? await prisma.trade.findMany({
      where: {
        userId: session.userId,
        symbol: session.symbol
      },
      orderBy: { createdAt: 'desc' },
      take: 10
    }) : []

    // Calculate metrics from actual trades
    const completedTrades = recentTrades.filter(t => t.status === 'COMPLETED')
    const activeTrades = recentTrades.filter(t => t.status === 'OPEN' || t.status === 'PENDING')
    
    // Calculate win rate
    const winRate = completedTrades.length > 0 ? 
      (completedTrades.filter(t => {
        const profit = t.profit || 0
        return profit > 0
      }).length / completedTrades.length * 100) : 0

    // Calculate daily P&L (trades from today)
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const todayTrades = completedTrades.filter(t => 
      new Date(t.createdAt) >= today
    )
    const dailyPnL = todayTrades.reduce((total, trade) => {
      const profit = trade.profit || 0
      return total + (typeof profit === 'string' ? parseFloat(profit) : profit)
    }, 0)

    // Calculate total P&L
    const totalPnL = completedTrades.reduce((total, trade) => {
      const profit = trade.profit || 0
      return total + (typeof profit === 'string' ? parseFloat(profit) : profit)
    }, 0)

    // Mock portfolio value (base amount + total P&L)
    const basePortfolioValue = 1000
    const portfolioValue = basePortfolioValue + totalPnL

    return NextResponse.json({
      status: 'connected',
      service: 'trading_bot',
      timestamp: new Date().toISOString(),
      health: 'healthy',
      
      // Trading status data for StatusOverview
      portfolioValue: portfolioValue,
      dailyPnL: dailyPnL,
      totalPnL: totalPnL,
      activeTrades: activeTrades.length,
      completedTrades: completedTrades.length,
      winRate: winRate,
      
      // Available coins (mock data for now)
      availableCoins: [
        {
          symbol: 'BTC',
          amount: 0.0156,
          price: 67840.25,
          usdValue: 1058.27
        },
        {
          symbol: 'SOL', 
          amount: 2.45,
          price: 99.85,
          usdValue: 244.63
        }
      ],

      // Market prices will be fetched separately
      marketPrices: []
    })
  } catch (error) {
    console.error('Status API error:', error)
    return NextResponse.json({
      status: 'error',
      service: 'trading_bot',
      error: error instanceof Error ? error.message : 'Unknown error',
      
      // Return default values so UI doesn't break
      portfolioValue: 1000,
      dailyPnL: 0,
      totalPnL: 0,
      activeTrades: 0,
      completedTrades: 0,
      winRate: 0,
      availableCoins: [],
      marketPrices: []
    }, { status: 500 })
  }
}
