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

const prisma = new PrismaClient()

export async function GET() {
  try {
    // Get recent AI decisions from database (last 10)
    const decisions = await prisma.ai_analysis_sessions.findMany({
      where: {
        // Get sessions with actual analysis data
        lastAnalysisData: {
          not: null
        }
      },
      orderBy: { 
        createdAt: 'desc' 
      },
      take: 10,
      select: {
        id: true,
        symbol: true,
        confidence: true,
        lastAnalysisData: true,
        createdAt: true,
        sessionId: true
      }
    })

    // Transform database records to match expected format
    const liveDecisions = decisions.map(session => {
      let analysisData = {}
      try {
        analysisData = JSON.parse(session.lastAnalysisData || '{}')
      } catch (e) {
        analysisData = {}
      }

      return {
        type: 'AI_DECISION',
        action: analysisData.recommendation?.toUpperCase() || 'HOLD',
        symbol: session.symbol,
        blocked: !(analysisData.recommendation?.toLowerCase().includes('buy') || analysisData.recommendation?.toLowerCase().includes('sell')),
        executed: false, // Always false for analysis decisions
        confidence: session.confidence || analysisData.confidence || 0,
        entryPrice: analysisData.entry?.price || analysisData.currentPrice || 0,
        stopLoss: analysisData.stopLoss?.price || analysisData.stopLoss || null,
        takeProfit: analysisData.takeProfits?.tp1?.price || analysisData.takeProfit || null,
        reasoning: analysisData.reasoning || analysisData.summary || 'AI market analysis',
        timestamp: session.createdAt.toISOString(),
        sessionId: session.sessionId
      }
    })
    
    const response = {
      success: true,
      decisions: liveDecisions,
      latest: liveDecisions[0] || null,
      timestamp: new Date().toISOString()
    }
    
    return NextResponse.json(response)
  } catch (error) {
    console.error('❌ Live decisions API error:', error)
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    )
  }
}

export async function POST(request) {
  try {
    const data = await request.json()
    
    // Store AI decision in database for persistence
    await prisma.ai_analysis_sessions.create({
      data: {
        id: `live_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        symbol: data.symbol || 'SOLUSD',
        confidence: data.confidence || 0,
        lastAnalysisData: JSON.stringify(data),
        sessionId: data.sessionId || `session_${Date.now()}`,
        createdAt: new Date()
      }
    })
    
    return NextResponse.json({ 
      success: true,
      message: 'Decision stored persistently',
      timestamp: new Date().toISOString() 
    })
  } catch (error) {
    console.error('❌ Error storing live decision:', error)
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    )
  }
}
