import { NextRequest, NextResponse } from 'next/server' import { placeExitOrders } from '@/lib/drift/orders' /** * Emergency endpoint to manually place exit orders * Use when orders vanish but position still exists */ export async function POST(req: NextRequest) { try { // Auth check const authHeader = req.headers.get('authorization') const apiSecret = process.env.API_SECRET_KEY if (!authHeader || !apiSecret || !authHeader.includes(apiSecret)) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const body = await req.json() const { symbol, direction, entryPrice, tp1Price, tp2Price, slPrice, positionSizeUSD, tp1SizePercent = 75, tp2SizePercent = 0, } = body // Validate required fields if (!symbol || !direction || !entryPrice || !tp1Price || !tp2Price || !slPrice || !positionSizeUSD) { return NextResponse.json({ success: false, error: 'Missing required fields' }, { status: 400 }) } console.log('🛡️ Manually placing exit orders for existing position...') console.log(` ${symbol} ${direction} @ $${entryPrice}`) console.log(` TP1: $${tp1Price} (${tp1SizePercent}%)`) console.log(` TP2: $${tp2Price} (${tp2SizePercent}%)`) console.log(` SL: $${slPrice}`) // Initialize Drift service BEFORE calling placeExitOrders const { initializeDriftService } = await import('@/lib/drift/client') await initializeDriftService() console.log('✅ Drift service ready for order placement') const result = await placeExitOrders({ symbol, direction, entryPrice, tp1Price, tp2Price, stopLossPrice: slPrice, positionSizeUSD, tp1SizePercent, tp2SizePercent, }) if (result.success) { console.log('✅ Exit orders placed successfully!') return NextResponse.json({ success: true, signatures: result.signatures, message: 'Exit orders placed on-chain' }) } else { console.error('❌ Failed to place exit orders:', result.error) return NextResponse.json({ success: false, error: result.error }, { status: 500 }) } } catch (error) { console.error('❌ Error in place-exit-orders:', error) return NextResponse.json({ success: false, error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 }) } }