import * as dotenv from 'dotenv';
import path from 'path';
import { AlpacaConnector } from '../src/connectors/alpaca.js';

async function testFullExecutionCycle() {
    console.log('--- Alpaca Full Cycle (Buy -> Sell) Test Start ---');
    dotenv.config({ path: path.resolve(process.cwd(), '.env') });

    const connector = new AlpacaConnector();
    const symbol = 'BTC/USD';
    const qty = 0.001; // Approx $95

    try {
        // 1. PLACE BUY ORDER
        console.log(`Step 1: Placing MARKET BUY for ${qty} ${symbol}...`);
        const buyOrder = await connector.placeOrder(symbol, 'buy', qty, 'market');
        if (buyOrder && buyOrder.id) {
            console.log(`✅ BUY SUCCESS: Order ID ${buyOrder.id}`);
        } else {
            throw new Error('Buy order failed - no ID returned');
        }

        // Wait a few seconds for the buy to process
        console.log('Waiting 3 seconds for position to register...');
        await new Promise(r => setTimeout(r, 3000));

        // 2. PLACE SELL ORDER (The real test for the user)
        console.log(`Step 2: Placing MARKET SELL for ${qty} ${symbol}...`);
        const sellOrder = await connector.placeOrder(symbol, 'sell', qty, 'market');
        if (sellOrder && sellOrder.id) {
            console.log(`✅ SELL SUCCESS: Order ID ${sellOrder.id}`);
        } else {
            throw new Error('Sell order failed - no ID returned');
        }

        console.log('\n--- FULL CYCLE VERIFIED SUCCESSFULLY ---');
    } catch (error: any) {
        console.log(`❌ FAILED: ${error.message || error}`);
    }

    console.log('--- Alpaca Full Cycle Test End ---');
}

testFullExecutionCycle().catch(console.error);
