import { config } from '../src/config/index.js';
import { AlpacaConnector } from '../src/connectors/alpaca.js';
import { TradeExecutor } from '../src/services/TradeExecutor.js';
import logger from '../src/utils/logger.js';

async function testFullLifeCycle() {
    logger.info('--- Starting FINAL E2E Trade Life Cycle Verification ---');

    // Use your specific user ID
    const userId = '8d5efd9e-0760-4859-8c07-0930ab3ede5a';
    const symbol = 'BTC/USD';
    const qty = 0.001;

    const exchange = new AlpacaConnector(config.ALPACA_API_KEY, config.ALPACA_API_SECRET);
    const executor = new TradeExecutor(exchange, undefined, userId);

    try {
        // 1. OPEN POSITION
        logger.info(`[Step 1] Opening Position for ${userId}...`);
        const openResult = await executor.openPosition(symbol, 'BUY' as any, qty, 'market');

        if (!openResult.success) {
            throw new Error(`Open failed: ${openResult.error}`);
        }
        logger.info(`✅ Open Processed: ${openResult.orderId}`);

        // Wait a bit for fill and status
        logger.info('Waiting 5 seconds for fill confirmation...');
        await new Promise(r => setTimeout(r, 5000));

        // 2. CLOSE POSITION
        logger.info(`[Step 2] Closing Position for ${userId}...`);
        const closeResult = await executor.closePosition(symbol, 'E2E_VERIFICATION_COMPLETE');

        if (!closeResult.success) {
            throw new Error(`Close failed: ${closeResult.error}`);
        }
        logger.info(`✅ Close Processed: Exit Price ${closeResult.exitPrice}`);

        // 3. FINAL WAIT FOR LOGGING
        logger.info('Waiting 10 seconds for all Supabase async logs to finish...');
        await new Promise(r => setTimeout(r, 10000));

        logger.info('--- E2E TEST COMPLETED ---');
        logger.info('Please check your Dashboard -> Trade History Tab.');
        logger.info(`Looking for entry: Symbol=${symbol}, Reason=E2E_VERIFICATION_COMPLETE`);

    } catch (error: any) {
        logger.error(`❌ TEST FAILED: ${error.message}`);
    }
}

testFullLifeCycle().catch(console.error);
