import { NextResponse } from 'next/server'
import { Connection, Keypair } from '@solana/web3.js'

export async function GET() {
  try {
    console.log('📊 Fetching real trading balance...')

    // Check if wallet is configured
    if (!process.env.SOLANA_PRIVATE_KEY) {
      return NextResponse.json({
        success: true,
        balance: {
          totalValue: 0,
          availableBalance: 0,
          positions: []
        },
        message: 'No wallet configured',
        timestamp: Date.now()
      })
    }

    // Get real wallet balance directly
    const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'
    const connection = new Connection(rpcUrl, 'confirmed')
    
    const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
    const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))

    // Get SOL balance
    const balance = await connection.getBalance(keypair.publicKey)
    const solBalance = balance / 1000000000

    // Get current SOL price
    const priceResponse = await fetch(
      'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_24hr_change=true'
    )
    
    const priceData = await priceResponse.json()
    const solPrice = priceData.solana?.usd || 0
    const change24h = priceData.solana?.usd_24h_change || 0
    const usdValue = solBalance * solPrice

    return NextResponse.json({
      success: true,
      balance: {
        totalValue: usdValue,
        availableBalance: usdValue,
        positions: [{
          symbol: 'SOL',
          price: solPrice,
          change24h: change24h,
          volume24h: 0,
          amount: solBalance,
          usdValue: usdValue
        }]
      },
      wallet: {
        publicKey: keypair.publicKey.toString(),
        solBalance: solBalance,
        usdValue: usdValue
      },
      timestamp: Date.now()
    })

  } catch (error) {
    console.error('❌ Balance API error:', error)
    return NextResponse.json({
      success: true,
      balance: {
        totalValue: 0,
        availableBalance: 0,
        positions: []
      },
      error: error.message,
      timestamp: Date.now()
    })
  }
}
