/**
 * Test Deposit API and Payment Methods
 * Run with: node test-deposit-api.js
 */

require('dotenv').config();
const mysql = require('mysql2/promise');
const KorapayService = require('./services/payments/KorapayService');
const CryptomusService = require('./services/payments/CryptomusService');

async function testDepositSystem() {
    console.log('\n🔧 Testing Deposit System\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');

        // Check payment methods
        console.log('📋 Checking Payment Methods in Database:\n');
        const [methods] = await connection.execute(`
            SELECT id, name, code, is_active, is_automated,
                   transaction_fee_percentage, min_amount, max_amount
            FROM payment_methods
            WHERE code IN ('korapay', 'cryptomus')
            ORDER BY id
        `);

        console.table(methods);

        if (methods.length === 0) {
            console.log('❌ No payment methods found! Run: node scripts/add-payment-methods.js\n');
            process.exit(1);
        }

        // Verify they are active
        const activeCount = methods.filter(m => m.is_active === 1).length;
        console.log(`\n✅ ${activeCount}/${methods.length} payment methods are active\n`);

        // Test Korapay
        console.log('='.repeat(60));
        console.log('🔑 Testing Korapay Service:\n');

        const korapay = new KorapayService();
        const korapayConfig = korapay.getConfig();

        console.log('Configuration:');
        console.log('  Mode:', korapayConfig.mode);
        console.log('  Name:', korapayConfig.name);
        console.log('  Automated:', korapayConfig.isAutomated);
        console.log('  Supports:', korapayConfig.supports.join(', '));

        console.log('\n📝 Environment Variables:');
        console.log('  KORAPAY_MODE:', process.env.KORAPAY_MODE || '❌ Not set');
        console.log('  KORAPAY_PUBLIC_KEY_TEST:', process.env.KORAPAY_PUBLIC_KEY_TEST ? '✅ Set' : '❌ Not set');
        console.log('  KORAPAY_SECRET_KEY_TEST:', process.env.KORAPAY_SECRET_KEY_TEST ? '✅ Set' : '❌ Not set');
        console.log('  KORAPAY_BASE_URL_TEST:', process.env.KORAPAY_BASE_URL_TEST || '❌ Not set');

        // Test payment initialization
        console.log('\n🔄 Testing Payment Initialization...');
        const testAmount = 1000;
        const testRef = `TEST_${Date.now()}`;

        const korapayResult = await korapay.initializePayment(testAmount, testRef, {
            user_id: 1,
            customer_name: 'Test User',
            customer_email: 'test@wakatraffic.ng'
        });

        if (korapayResult.success) {
            console.log('✅ Korapay initialization successful!');
            console.log('   Payment URL:', korapayResult.data.payment_url);
            console.log('   Reference:', korapayResult.data.reference);
        } else {
            console.log('❌ Korapay initialization failed:', korapayResult.message);
        }

        // Test Cryptomus
        console.log('\n' + '='.repeat(60));
        console.log('🪙 Testing Cryptomus Service:\n');

        const cryptomus = new CryptomusService();
        const cryptomusConfig = cryptomus.getConfig();

        console.log('Configuration:');
        console.log('  Name:', cryptomusConfig.name);
        console.log('  Type:', cryptomusConfig.type);
        console.log('  Automated:', cryptomusConfig.isAutomated);
        console.log('  Exchange Rate:', cryptomusConfig.exchangeRate, 'NGN/USD');

        console.log('\n📝 Environment Variables:');
        console.log('  CRYPTOMUS_MERCHANT_ID:', process.env.CRYPTOMUS_MERCHANT_ID || '❌ Not set');
        console.log('  CRYPTOMUS_API_KEY:', process.env.CRYPTOMUS_API_KEY ? '✅ Set' : '❌ Not set');
        console.log('  CRYPTOMUS_PAYMENT_API_KEY:', process.env.CRYPTOMUS_PAYMENT_API_KEY ? '✅ Set' : '❌ Not set');
        console.log('  CRYPTOMUS_BASE_URL:', process.env.CRYPTOMUS_BASE_URL || '❌ Not set');

        // Test crypto payment (will fail without real merchant ID)
        console.log('\n🔄 Testing Crypto Payment Initialization...');
        const cryptoTestAmount = 50000;
        const cryptoTestRef = `TEST_CRYPTO_${Date.now()}`;

        const cryptomusResult = await cryptomus.initializePayment(cryptoTestAmount, cryptoTestRef, {
            user_id: 1,
            crypto_currency: 'USDT'
        });

        if (cryptomusResult.success) {
            console.log('✅ Cryptomus initialization successful!');
            console.log('   Payment URL:', cryptomusResult.data.payment_url);
            console.log('   Amount NGN:', cryptomusResult.data.amount_ngn);
            console.log('   Amount USD:', cryptomusResult.data.amount_usd);
        } else {
            console.log('⚠️  Cryptomus initialization failed:', cryptomusResult.message);
            if (cryptomusResult.message.includes('Merchant')) {
                console.log('   NOTE: Update CRYPTOMUS_MERCHANT_ID in .env with real value from dashboard');
            }
        }

        // Summary
        console.log('\n' + '='.repeat(60));
        console.log('✅ TEST SUMMARY\n');
        console.log('Database:');
        console.log('  ✅ Payment methods: ' + methods.length);
        console.log('  ✅ Active methods: ' + activeCount);

        console.log('\nKorapay:');
        console.log('  ' + (korapayResult.success ? '✅' : '❌') + ' Test mode working');
        console.log('  ' + (process.env.KORAPAY_PUBLIC_KEY_TEST ? '✅' : '❌') + ' API keys configured');

        console.log('\nCryptomus:');
        console.log('  ' + (cryptomusResult.success ? '✅' : '⚠️ ') + ' ' + (cryptomusResult.success ? 'Working' : 'Needs merchant ID'));
        console.log('  ' + (process.env.CRYPTOMUS_API_KEY ? '✅' : '❌') + ' API keys configured');

        console.log('\n📌 Next Steps:');
        console.log('1. Start server: npm run dev');
        console.log('2. Open browser: http://localhost:5000/deposit.html');
        console.log('3. Select Korapay or Cryptomus');
        console.log('4. Enter amount and click Pay');
        console.log('5. Complete payment in popup window\n');

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

// Run tests
testDepositSystem();
