import { NextRequest, NextResponse } from 'next/server'
import { supabase } from '@/lib/supabase'

export async function GET() {
  try {
    const { data: trades, error } = await supabase
      .from('trades')
      .select('*')
      .order('opened_at', { ascending: false })
    
    if (error) throw error
    
    return NextResponse.json({ trades: trades || [] })
  } catch (error) {
    console.error('Supabase error:', error)
    return NextResponse.json({ trades: [], error: 'Failed to fetch' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    
    // Convert camelCase to snake_case for Supabase
    const trade = {
      pair: body.pair || body.pair,
      direction: body.direction,
      entry_price: body.entryPrice || body.entry_price,
      exit_price: body.exitPrice || body.exit_price,
      status: body.status || 'open',
      is_demo: body.isDemo ?? body.is_demo ?? true,
      trader_style: body.traderStyle || body.trader_style,
      setup: body.setup,
      timeframe: body.timeframe,
      pnl: body.pnl,
      opened_at: new Date().toISOString(),
    }
    
    const { data, error } = await supabase
      .from('trades')
      .insert([trade])
      .select()
    
    if (error) {
      console.error('Supabase insert error:', error)
      return NextResponse.json({ error: error.message }, { status: 500 })
    }
    
    return NextResponse.json({ success: true, trade: data?.[0] })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ error: 'Failed to save' }, { status: 500 })
  }
}
