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.automation_sessions.findFirst({ orderBy: { createdAt: 'desc' } }) // Get recent trades for calculations const recentTrades = session ? await prisma.trades.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 // Get REAL available coins from Drift positions const driftResponse = await fetch(`${process.env.APP_URL || 'http://localhost:3000'}/api/drift/positions`); let availableCoins = ['SOL']; // fallback if (driftResponse.ok) { const positionsData = await driftResponse.json(); if (positionsData.success && positionsData.positions) { availableCoins = positionsData.positions.map((pos: any) => pos.symbol || 'SOL'); } } 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, availableCoins: availableCoins, // 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 }) } }