import * as dotenv from 'dotenv';
dotenv.config();
import { ConnectorFactory } from '../src/connectors/factory.js';
import { TradeExecutor } from '../src/services/TradeExecutor.js';
import { ManualTrader } from '../src/services/ManualTrader.js';
import { supabaseService } from '../src/services/SupabaseService.js';
import { config } from '../src/config/index.js';
import { SignalDirection } from '../src/strategies/rules/types.js';
import logger from '../src/utils/logger.js';

async function verifyFullCycleWithSL() {
    console.log("--- 🚀 STARTING FULL CYCLE VERIFICATION (SL/TP PERSISTENCE) ---");

    const testUserId = "550e8400-e29b-41d4-a716-446655440000"; // Fake UUID for test
    const symbol = "BTC/USDT";
    const qty = 0.0002; // Smallest safe qty for Alpaca
    const sl = 80000;
    const tp = 110000;

    // 1. Setup
    const exchange = ConnectorFactory.getCustomConnector(
        config.EXECUTION_PROVIDER,
        config.ALPACA_API_KEY!,
        config.ALPACA_API_SECRET!
    );
    const executor = new TradeExecutor(exchange, undefined, 'global');
    const manualTrader = new ManualTrader(executor);

    console.log(`\nSTEP 1: Opening Manual Position for ${symbol}...`);
    const openResult = await manualTrader.executeRequest(
        symbol,
        'buy',
        qty,
        'market',
        undefined,
        testUserId,
        sl,
        tp
    );

    if (!openResult.success) {
        console.error("❌ Open Failed:", openResult.error);
        return;
    }
    console.log("✅ Position Opened. Order ID:", openResult.orderId);

    // 2. Verify persistence in DB
    console.log("\nSTEP 2: Verifying SL/TP Persistence in Supabase...");
    // Artificial delay for DB write
    await new Promise(r => setTimeout(r, 2000));

    const latestOrder = await supabaseService.getLatestOrder(testUserId, symbol);
    if (latestOrder && latestOrder.stop_loss === sl && latestOrder.take_profit === tp) {
        console.log(`✅ SL/TP VERIFIED in DB: SL=${latestOrder.stop_loss}, TP=${latestOrder.take_profit}`);
    } else {
        console.error("❌ DB Verification Failed!", latestOrder);
    }

    // 3. Verify Recovery (Simulate Restart)
    console.log("\nSTEP 3: Simulating Bot Restart (Recovery from DB)...");
    const newExecutor = new TradeExecutor(exchange, undefined, testUserId);
    await newExecutor.syncPositions([symbol]);

    const recoveredPos = newExecutor.getActivePosition(symbol);
    if (recoveredPos && recoveredPos.stopLoss === sl && recoveredPos.userId === testUserId) {
        console.log(`✅ RECOVERY VERIFIED: Recovered SL=${recoveredPos.stopLoss} for User=${recoveredPos.userId}`);
    } else {
        console.error("❌ Recovery Failed!", recoveredPos);
    }

    // 4. Close Position
    console.log("\nSTEP 4: Closing Position...");
    const closeResult = await newExecutor.closePosition(symbol, "Test Verification Close");
    if (closeResult.success) {
        console.log("✅ Position Closed.");
    } else {
        console.error("❌ Close Failed:", closeResult.error);
    }

    console.log("\n--- ✨ VERIFICATION COMPLETE ---");
}

verifyFullCycleWithSL().catch(console.error);
