import { supabaseService } from '../src/services/SupabaseService';
import { createClient } from '@supabase/supabase-js';
import * as dotenv from 'dotenv';
import logger from '../src/utils/logger';
dotenv.config();

const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_KEY!);

async function verify() {
    console.log("Starting Realtime Verification Test...");

    let eventReceived = false;

    // 1. Setup Listener
    const subscription = supabaseService.subscribeToProfiles((payload) => {
        console.log("🔥 REALTIME EVENT RECEIVED:", payload.eventType);
        eventReceived = true;
    });

    if (!subscription) {
        console.error("Failed to subscribe");
        return;
    }

    console.log("Waiting for subscription to settle...");
    await new Promise(r => setTimeout(r, 2000));

    // 2. Find User
    const { data: users } = await supabase.from('users').select('user_id').limit(1);
    const userId = users![0].user_id;

    // 3. Trigger Event
    console.log("Triggering INSERT...");
    const testName = `VERIFY_SIGNAL_${Date.now()}`;
    await supabase.from('trade_profiles').insert([{
        user_id: userId,
        name: testName,
        allocated_capital: 1,
        is_active: false
    }]);

    // 4. Wait & Check
    await new Promise(r => setTimeout(r, 5000));

    if (eventReceived) {
        console.log("✅ SUCCESS: Realtime listener caught the database event.");
    } else {
        console.error("❌ FAILURE: Realtime listener did not trigger.");
    }

    // Cleanup
    await supabase.from('trade_profiles').delete().eq('name', testName);
    process.exit(eventReceived ? 0 : 1);
}

verify();
