import { createClient } from '@supabase/supabase-js';
import * as dotenv from 'dotenv';
dotenv.config();

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

const userContexts = new Map<string, any>();

async function simulateBot() {
    console.log("🤖 Simulated Bot: Listening for profile changes...");

    const sub = supabase
        .channel('test_channel')
        .on('postgres_changes', { event: '*', schema: 'public', table: 'trade_profiles' }, (payload) => {
            const { eventType, new: newRec, old: oldRec } = payload as any;
            console.log(`\n🔔 Neural Event Received: ${eventType}`);

            if (eventType === 'INSERT' || eventType === 'UPDATE') {
                if (newRec.is_active) {
                    if (userContexts.has(newRec.id)) {
                        console.log(`   🔄 Hot-Swap: Refreshing [${newRec.name}]`);
                    } else {
                        console.log(`   🚀 Hot-Load: Starting [${newRec.name}] with capital $${newRec.allocated_capital}`);
                    }
                    userContexts.set(newRec.id, newRec);
                } else {
                    if (userContexts.has(newRec.id)) {
                        console.log(`   🔻 Hot-Remove: Terminating [${newRec.name}] (Inactive)`);
                        userContexts.delete(newRec.id);
                    }
                }
            } else if (eventType === 'DELETE') {
                console.log(`   🔻 Hot-Remove: Profile ${oldRec.id} Deleted`);
                userContexts.delete(oldRec.id);
            }
        });

    sub.subscribe((status) => {
        console.log(`   📡 Subscription Status: ${status}`);
    });

    // Giving it time to connect
    console.log("   Waiting for realtime connection...");
    await new Promise(r => setTimeout(r, 5000));

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

    // Trigger INSERT
    const profileName = `VERIFY_${Date.now()}`;
    console.log(`\n--- Action: Creating profile ${profileName} ---`);
    const { data: ins } = await supabase.from('trade_profiles').insert([{ user_id: userId, name: profileName, allocated_capital: 777, is_active: true }]).select();
    if (!ins) {
        console.error("Failed to insert profile. Database probably has RLS enabled or constraints.");
        process.exit(1);
    }
    const id = ins![0].id;

    await new Promise(r => setTimeout(r, 4000));

    // Trigger UPDATE
    console.log(`\n--- Action: Updating capital to $888 ---`);
    await supabase.from('trade_profiles').update({ allocated_capital: 888 }).eq('id', id);

    await new Promise(r => setTimeout(r, 4000));

    // Trigger DELETE
    console.log(`\n--- Action: Deleting profile ---`);
    await supabase.from('trade_profiles').delete().eq('id', id);

    await new Promise(r => setTimeout(r, 4000));
    console.log("\n✅ Simulation Complete.");
    process.exit(0);
}

simulateBot();
