/**
 * Test Payment Gateway Integration
 * Tests Korapay and Cryptomus services
 * Run with: node test-payment-integration.js
 */

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

console.log('\n🔧 Testing Payment Gateway Integration\n');
console.log('=' .repeat(60));

// Initialize services
const korapay = new KorapayService();
const cryptomus = new CryptomusService();

/**
 * Test Korapay Service
 */
async function testKorapay() {
    console.log('\n📦 Testing Korapay Service');
    console.log('-'.repeat(60));

    try {
        // Test configuration
        const config = korapay.getConfig();
        console.log('✅ Configuration:', JSON.stringify(config, null, 2));

        // Test payment initialization
        console.log('\n🔄 Testing payment initialization...');
        const amount = 1000; // ₦1,000
        const reference = `TEST_KRP_${Date.now()}`;
        const metadata = {
            user_id: 1,
            customer_name: 'Test User',
            customer_email: 'test@wakatraffic.ng'
        };

        const initResult = await korapay.initializePayment(amount, reference, metadata);

        if (initResult.success) {
            console.log('✅ Payment Initialization SUCCESS');
            console.log('   Reference:', initResult.data.reference);
            console.log('   Payment URL:', initResult.data.payment_url);
            console.log('   Expires At:', initResult.data.expires_at);

            // Test payment status
            console.log('\n🔍 Testing payment status check...');
            const statusResult = await korapay.getPaymentStatus(reference);
            console.log('   Status:', statusResult);

        } else {
            console.log('❌ Payment Initialization FAILED');
            console.log('   Error:', initResult.message);
        }

    } catch (error) {
        console.error('❌ Korapay Test Error:', error.message);
    }
}

/**
 * Test Cryptomus Service
 */
async function testCryptomus() {
    console.log('\n\n📦 Testing Cryptomus Service');
    console.log('-'.repeat(60));

    try {
        // Test configuration
        const config = cryptomus.getConfig();
        console.log('✅ Configuration:', JSON.stringify(config, null, 2));

        // Test NGN to USD conversion
        console.log('\n💱 Testing currency conversion...');
        const amountNGN = 50000;
        const amountUSD = cryptomus.convertNGNtoUSD(amountNGN);
        console.log(`   ₦${amountNGN.toLocaleString()} = $${amountUSD} USD`);

        // Test payment initialization
        console.log('\n🔄 Testing crypto payment initialization...');
        const reference = `TEST_CRP_${Date.now()}`;
        const metadata = {
            user_id: 1,
            crypto_currency: 'USDT'
        };

        const initResult = await cryptomus.initializePayment(amountNGN, reference, metadata);

        if (initResult.success) {
            console.log('✅ Crypto Payment Initialization SUCCESS');
            console.log('   Reference:', initResult.data.reference);
            console.log('   Payment URL:', initResult.data.payment_url);
            console.log('   Amount NGN:', `₦${initResult.data.amount_ngn.toLocaleString()}`);
            console.log('   Amount USD:', `$${initResult.data.amount_usd}`);
            console.log('   Crypto Currency:', initResult.data.crypto_currency);

            // Test payment status
            console.log('\n🔍 Testing crypto payment status check...');
            const statusResult = await cryptomus.getPaymentStatus(reference);
            console.log('   Status:', statusResult);

        } else {
            console.log('❌ Crypto Payment Initialization FAILED');
            console.log('   Error:', initResult.message);

            if (initResult.message.includes('merchant_id') || initResult.message.includes('CRYPTOMUS_MERCHANT_ID')) {
                console.log('\n⚠️  NOTE: Set CRYPTOMUS_MERCHANT_ID in .env to test live payments');
            }
        }

        // Test supported currencies (optional)
        console.log('\n🪙 Testing supported currencies...');
        const currenciesResult = await cryptomus.getSupportedCurrencies();

        if (currenciesResult.success) {
            console.log('✅ Supported Currencies Retrieved');
            console.log(`   Total: ${currenciesResult.data.length || 'Unknown'} cryptocurrencies`);
        } else {
            console.log('⚠️  Could not fetch currencies:', currenciesResult.message);
        }

    } catch (error) {
        console.error('❌ Cryptomus Test Error:', error.message);
    }
}

/**
 * Test Webhook Signature Verification
 */
function testWebhookSignatures() {
    console.log('\n\n🔐 Testing Webhook Signature Verification');
    console.log('-'.repeat(60));

    // Test Korapay signature
    console.log('\n📝 Korapay Webhook Signature:');
    const korapayPayload = JSON.stringify({ event: 'charge.success', data: { reference: 'TEST123' } });
    const korapaySignature = 'test_signature_123';
    const korapayValid = korapay.verifyWebhookSignature(korapayPayload, korapaySignature);
    console.log('   Signature Valid:', korapayValid ? '✅ YES' : '⚠️  NO (Expected in test mode without secret)');

    // Test Cryptomus signature
    console.log('\n📝 Cryptomus Webhook Signature:');
    const cryptomusPayload = { status: 'paid', order_id: 'TEST123' };
    const cryptomusSignature = cryptomus.generateSignature(cryptomusPayload);
    console.log('   Generated Signature:', cryptomusSignature);
    console.log('   Signature Format:', '✅ MD5 Hash');
}

/**
 * Display Environment Check
 */
function checkEnvironment() {
    console.log('\n\n⚙️  Environment Configuration');
    console.log('-'.repeat(60));

    console.log('\n🔑 Korapay:');
    console.log('   Mode:', process.env.KORAPAY_MODE || 'Not set');
    console.log('   Public Key (Test):', process.env.KORAPAY_PUBLIC_KEY_TEST ? '✅ Set' : '❌ Missing');
    console.log('   Secret Key (Test):', process.env.KORAPAY_SECRET_KEY_TEST ? '✅ Set' : '❌ Missing');
    console.log('   Public Key (Live):', process.env.KORAPAY_PUBLIC_KEY_LIVE ? '✅ Set' : '⚠️  Not set');
    console.log('   Secret Key (Live):', process.env.KORAPAY_SECRET_KEY_LIVE ? '✅ Set' : '⚠️  Not set');
    console.log('   Base URL (Test):', process.env.KORAPAY_BASE_URL_TEST || 'Not set');
    console.log('   Webhook Secret:', process.env.KORAPAY_WEBHOOK_SECRET ? '✅ Set' : '⚠️  Not set');

    console.log('\n🔑 Cryptomus:');
    console.log('   Merchant ID:', process.env.CRYPTOMUS_MERCHANT_ID || '⚠️  Not set');
    console.log('   API Key:', process.env.CRYPTOMUS_API_KEY ? '✅ Set' : '❌ Missing');
    console.log('   Payment API Key:', process.env.CRYPTOMUS_PAYMENT_API_KEY ? '✅ Set' : '❌ Missing');
    console.log('   Base URL:', process.env.CRYPTOMUS_BASE_URL || 'Not set');
    console.log('   Exchange Rate (NGN/USD):', process.env.CRYPTOMUS_EXCHANGE_RATE_NGN_USD || '1600 (default)');
}

/**
 * Run all tests
 */
async function runTests() {
    console.log('\n🚀 WakaTraffic Payment Gateway Integration Test Suite\n');

    // Environment check
    checkEnvironment();

    // Test services
    await testKorapay();
    await testCryptomus();

    // Test webhook signatures
    testWebhookSignatures();

    // Summary
    console.log('\n\n' + '='.repeat(60));
    console.log('✅ Test Suite Complete!');
    console.log('='.repeat(60));
    console.log('\n📌 Next Steps:');
    console.log('   1. Start server: npm run dev');
    console.log('   2. Test API: POST /api/deposits/initialize');
    console.log('   3. Configure webhooks on provider dashboards');
    console.log('   4. Update live credentials before production\n');
}

// Run tests
runTests().catch(console.error);
