
import { supabaseService } from '../src/services/SupabaseService.js';
import logger from '../src/utils/logger.js';

async function debugDatabaseLogging() {
    logger.info('🔍 Starting Database Logging Debug...');

    // 1. Get Real User & Profile
    const profiles = await supabaseService.getActiveProfiles();
    if (profiles.length === 0) {
        logger.error('No profiles found to test with.');
        return;
    }
    const profile = profiles[0];
    const user = profile.users;

    logger.info(`👤 Testing with Profile: ${profile.name} (${profile.id})`);
    logger.info(`👤 Testing with User: ${user.email} (${user.user_id})`);

    // 2. Test Order Logging
    const testOrder = {
        user_id: user.user_id,
        profile_id: profile.id, // Explicitly testing this link
        order_id: `test-order-${Date.now()}`,
        symbol: 'BTC/USD',
        type: 'market',
        side: 'buy',
        qty: 0.1,
        price: 50000,
        status: 'filled',
        timestamp: Date.now()
    };

    logger.info('📝 Attempting to insert Order:', testOrder);

    // Call private client directly to get full error if service swallows it
    // @ts-ignore
    const { data: orderData, error: orderError } = await supabaseService.client
        .from('orders')
        .insert([testOrder])
        .select();

    if (orderError) {
        logger.error('❌ ORDER LOGGING FAILED:');
        logger.error(JSON.stringify(orderError, null, 2));
    } else {
        logger.info('✅ ORDER LOGGING SUCCESS:', orderData);
    }

    // 3. Test Trade History Logging
    const testTrade = {
        user_id: user.user_id,
        profile_id: profile.id,
        symbol: 'BTC/USD',
        side: 'BUY',
        entry_price: 50000,
        exit_price: 55000,
        size: 0.1,
        pnl: 500,
        pnl_percent: 10,
        reason: 'Debug Test',
        timestamp: Date.now()
    };

    logger.info('📝 Attempting to insert Trade History:', testTrade);

    // @ts-ignore
    const { data: tradeData, error: tradeError } = await supabaseService.client
        .from('trade_history')
        .insert([testTrade])
        .select();

    if (tradeError) {
        logger.error('❌ TRADE LOGGING FAILED:');
        logger.error(JSON.stringify(tradeError, null, 2));
    } else {
        logger.info('✅ TRADE LOGGING SUCCESS:', tradeData);

        // Cleanup (Consistency)
        logger.info('🧹 Cleaning up test data...');
        // @ts-ignore
        await supabaseService.client.from('orders').delete().eq('order_id', testOrder.order_id);
    }
}

debugDatabaseLogging();
