import { createClient } from '@supabase/supabase-js';
import { config } from '../src/config/index.js';

async function seedTestData() {
    console.log('--- SEEDING TEST DATA FOR PROFILES ---');

    if (!config.SUPABASE_URL || !config.SUPABASE_KEY) {
        console.error('Supabase credentials missing.');
        return;
    }

    const supabase = createClient(config.SUPABASE_URL, config.SUPABASE_KEY);

    // 1. Get all profiles
    const { data: profiles, error: pError } = await supabase
        .from('trade_profiles')
        .select('*');

    if (pError || !profiles) {
        console.error('Error fetching profiles:', pError?.message);
        return;
    }

    console.log(`Found ${profiles.length} profiles to seed.`);

    const symbols = ['BTC/USD', 'ETH/USD', 'AAPL', 'TSLA', 'NVDA', 'SOL/USD'];

    for (const profile of profiles) {
        console.log(`Seeding data for profile: ${profile.name}...`);

        const userId = profile.user_id;
        const profileId = profile.id;

        // Generate 2-3 mock history records
        const recordsCount = 2 + Math.floor(Math.random() * 2);
        const historyEntries = [];
        const orderEntries = [];

        for (let i = 0; i < recordsCount; i++) {
            const sym = symbols[Math.floor(Math.random() * symbols.length)];
            const entryPrice = 100 + Math.random() * 1000;
            const pnlPercent = (Math.random() * 10) - 4; // -4% to +6%
            const exitPrice = entryPrice * (1 + (pnlPercent / 100));
            const size = 1 + Math.random() * 5;
            const pnl = (exitPrice - entryPrice) * size;

            historyEntries.push({
                user_id: userId,
                profile_id: profileId,
                symbol: sym,
                side: 'BUY',
                entry_price: entryPrice,
                exit_price: exitPrice,
                size: size,
                pnl: pnl,
                pnl_percent: pnlPercent,
                reason: 'STRATEGY_SIGNAL_AUTO',
                timestamp: Math.floor(Date.now() - (i * 86400000) - (Math.random() * 1000000)),
            });

            // Add a corresponding order for the latest trade
            orderEntries.push({
                user_id: userId,
                profile_id: profileId,
                order_id: `test-ord-${Math.random().toString(36).substring(7)}`,
                symbol: sym,
                type: 'Market',
                side: 'buy',
                qty: size,
                price: entryPrice,
                status: 'Filled',
                timestamp: Math.floor(Date.now() - (i * 86400000) - 500000)
            });
        }

        // Insert History
        const { error: hError } = await supabase.from('trade_history').insert(historyEntries);
        if (hError) console.error(`Error inserting history for ${profile.name}:`, hError.message);
        else console.log(`✅ Inserted ${historyEntries.length} history records for ${profile.name}`);

        // Insert Orders
        const { error: oError } = await supabase.from('orders').insert(orderEntries);
        if (oError) console.error(`Error inserting orders for ${profile.name}:`, oError.message);
        else console.log(`✅ Inserted ${orderEntries.length} order records for ${profile.name}`);
    }

    console.log('\n--- SEEDING COMPLETE ---');
}

seedTestData().catch(console.error);
