/**
 * Fund Demo Account with 50,000 Naira
 * Run with: node fund-demo-account.js
 */

require('dotenv').config();
const mysql = require('mysql2/promise');

async function fundDemoAccount() {
    console.log('\n💰 Funding Demo Account\n');
    console.log('='.repeat(60));

    let connection;

    try {
        // Connect to database
        connection = await mysql.createConnection({
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME,
            port: process.env.DB_PORT
        });

        console.log('✅ Connected to database\n');

        // Find the demo/test account
        const [users] = await connection.execute(`
            SELECT id, email, first_name, last_name, balance
            FROM users
            ORDER BY id ASC
            LIMIT 1
        `);

        if (users.length === 0) {
            console.log('❌ No users found in database!');
            console.log('   Create a user first\n');
            process.exit(1);
        }

        const user = users[0];
        const fundAmount = 50000;
        const currentBalance = parseFloat(user.balance || 0);
        const newBalance = currentBalance + fundAmount;

        console.log('📋 Demo Account Details:');
        console.log('   User ID:', user.id);
        console.log('   Email:', user.email);
        console.log('   Name:', `${user.first_name} ${user.last_name}`);
        console.log('   Current Balance:', `₦${currentBalance.toLocaleString()}`);
        console.log('   Amount to Add:', `₦${fundAmount.toLocaleString()}`);
        console.log('   New Balance:', `₦${newBalance.toLocaleString()}\n`);

        // Update user balance
        await connection.execute(`
            UPDATE users
            SET balance = ?,
                updated_at = NOW()
            WHERE id = ?
        `, [newBalance, user.id]);

        console.log('✅ Balance updated successfully!\n');

        // Create transaction record
        await connection.execute(`
            INSERT INTO transactions (
                user_id,
                type,
                amount,
                charge,
                post_balance,
                description,
                reference_id,
                created_at
            ) VALUES (?, 'credit', ?, 0, ?, ?, ?, NOW())
        `, [
            user.id,
            fundAmount,
            newBalance,
            'Demo Account Funding - Testing Credit',
            'DEMO_FUND_' + Date.now()
        ]);

        console.log('✅ Transaction record created\n');

        // Create deposit record
        const [paymentMethods] = await connection.execute(`
            SELECT id FROM payment_methods LIMIT 1
        `);

        if (paymentMethods.length > 0) {
            await connection.execute(`
                INSERT INTO deposits (
                    user_id,
                    payment_method_id,
                    reference,
                    amount,
                    fee,
                    amount_credited,
                    currency,
                    status,
                    paid_at,
                    verified_at,
                    completed_at,
                    created_at,
                    updated_at
                ) VALUES (?, ?, ?, ?, 0, ?, 'NGN', 'completed', NOW(), NOW(), NOW(), NOW(), NOW())
            `, [
                user.id,
                paymentMethods[0].id,
                'DEMO_DEPOSIT_' + Date.now(),
                fundAmount,
                fundAmount
            ]);

            console.log('✅ Deposit record created\n');
        }

        // Verify the update
        const [updatedUser] = await connection.execute(`
            SELECT balance FROM users WHERE id = ?
        `, [user.id]);

        console.log('='.repeat(60));
        console.log('✅ Demo Account Funded Successfully!\n');
        console.log('📊 Final Balance:', `₦${parseFloat(updatedUser[0].balance).toLocaleString()}`);
        console.log('\n🔑 Demo Account Login:');
        console.log('   Email:', user.email);
        console.log('   Available Balance:', `₦${parseFloat(updatedUser[0].balance).toLocaleString()}\n`);
        console.log('🎯 You can now:');
        console.log('   - Login at: http://localhost:5000/login.html');
        console.log('   - Make test orders');
        console.log('   - Test deposit features');
        console.log('   - View transaction history\n');

    } catch (error) {
        console.error('\n❌ Error:', error.message);
        process.exit(1);
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

// Run
fundDemoAccount();
