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

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

async function fundAccount() {
    console.log('\n💰 Funding Account: user@wakatraffic.demo\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 specific account
        const [users] = await connection.execute(`
            SELECT id, email, first_name, last_name, balance
            FROM users
            WHERE email = ?
        `, ['user@wakatraffic.demo']);

        if (users.length === 0) {
            console.log('❌ User not found: user@wakatraffic.demo');
            console.log('   Creating demo account...\n');

            // Create the demo account
            const bcrypt = require('bcrypt');
            const hashedPassword = await bcrypt.hash('demo123', 10);

            const [result] = await connection.execute(`
                INSERT INTO users (
                    email,
                    password,
                    first_name,
                    last_name,
                    mobile_number,
                    balance,
                    role,
                    status,
                    created_at,
                    updated_at
                ) VALUES (?, ?, ?, ?, ?, 0, 'user', 'active', NOW(), NOW())
            `, [
                'user@wakatraffic.demo',
                hashedPassword,
                'Demo',
                'User',
                '08012345678'
            ]);

            const newUserId = result.insertId;
            console.log('✅ Demo account created!');
            console.log('   User ID:', newUserId);
            console.log('   Email: user@wakatraffic.demo');
            console.log('   Password: demo123\n');

            // Re-fetch the user
            const [newUsers] = await connection.execute(`
                SELECT id, email, first_name, last_name, balance
                FROM users
                WHERE id = ?
            `, [newUserId]);

            users.push(newUsers[0]);
        }

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

        console.log('📋 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 - WakaTraffic Testing',
            'DEMO_FUND_' + Date.now()
        ]);

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

        // Create deposit record
        const [paymentMethods] = await connection.execute(`
            SELECT id FROM payment_methods WHERE code IN ('korapay', 'cryptomus') 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_DEP_' + 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('✅ Account Funded Successfully!\n');
        console.log('📊 Final Balance:', `₦${parseFloat(updatedUser[0].balance).toLocaleString()}`);
        console.log('\n🔑 Login Credentials:');
        console.log('   Email: user@wakatraffic.demo');
        console.log('   Password: demo123');
        console.log('   Balance: ₦' + parseFloat(updatedUser[0].balance).toLocaleString() + '\n');
        console.log('🎯 Quick Start:');
        console.log('   1. Login at: http://localhost:5000/login.html');
        console.log('   2. Email: user@wakatraffic.demo');
        console.log('   3. Password: demo123');
        console.log('   4. Start placing orders!\n');

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

// Run
fundAccount();
