import { NextResponse } from 'next/server';

export async function POST(request) {
  try {
    console.log('🧹 CANCELING ALL ORDERS');
    
    // Import Drift SDK
    const { DriftClient, initialize, Wallet } = await import('@drift-labs/sdk');
    const { Connection, Keypair } = await import('@solana/web3.js');
    
    // Setup connection and wallet
    const rpcEndpoint = process.env.SOLANA_RPC_URL || 'https://mainnet.helius-rpc.com/?api-key=5e236449-f936-4af7-ae38-f15e2f1a3757';
    const connection = new Connection(rpcEndpoint, 'confirmed');
    
    if (!process.env.SOLANA_PRIVATE_KEY) {
      return NextResponse.json({
        success: false,
        error: 'SOLANA_PRIVATE_KEY not configured'
      }, { status: 400 });
    }
    
    const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY);
    const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray));
    const wallet = new Wallet(keypair);
    
    // Initialize Drift client
    const env = 'mainnet-beta';
    const sdkConfig = initialize({ env });
    const driftClient = new DriftClient({
      connection,
      wallet,
      programID: sdkConfig.DRIFT_PROGRAM_ID,
      accountSubscription: {
        type: 'polling',
        accountLoader: {
          commitment: 'confirmed'
        }
      }
    });
    
    await driftClient.subscribe();
    
    // Get all open orders
    const user = driftClient.getUser();
    const orders = user.getOpenOrders();
    
    console.log(`📋 Found ${orders.length} open orders to cancel`);
    
    const cancelResults = [];
    let successCount = 0;
    let failCount = 0;
    
    // Cancel orders in batches to avoid rate limits
    const batchSize = 5;
    for (let i = 0; i < orders.length; i += batchSize) {
      const batch = orders.slice(i, i + batchSize);
      
      const batchPromises = batch.map(async (order) => {
        try {
          console.log(`🚫 Canceling order ${order.orderId}...`);
          
          const txSig = await driftClient.cancelOrder(order.orderId);
          
          console.log(`   ✅ Order ${order.orderId} canceled: ${txSig}`);
          successCount++;
          
          return {
            orderId: order.orderId,
            success: true,
            txSig: txSig
          };
          
        } catch (error) {
          console.log(`   ❌ Failed to cancel order ${order.orderId}: ${error.message}`);
          failCount++;
          
          return {
            orderId: order.orderId,
            success: false,
            error: error.message
          };
        }
      });
      
      const batchResults = await Promise.allSettled(batchPromises);
      cancelResults.push(...batchResults.map(r => r.value || r.reason));
      
      // Small delay between batches
      if (i + batchSize < orders.length) {
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
    
    await driftClient.unsubscribe();
    
    console.log(`✅ Order cancellation complete: ${successCount} success, ${failCount} failed`);
    
    return NextResponse.json({
      success: true,
      message: `Canceled ${successCount} orders`,
      totalOrders: orders.length,
      totalCanceled: successCount,
      totalFailed: failCount,
      results: cancelResults
    });
    
  } catch (error) {
    console.error('❌ Cancel all orders error:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to cancel orders',
      details: error.message
    }, { status: 500 });
  }
}
