require('dotenv').config();
const axios = require('axios');

// Configuration object
const config = {
    // Replace with your actual domain/IP
    webhookUrl: process.env.WEBHOOK_URL || 'https://your-coolify-domain/api/match-notification',
    webhookSecret: process.env.WEBHOOK_SECRET,
    testCases: [
        {
            name: 'Basic Connectivity',
            data: {
                type: 'match_request',
                game_name: "Echo Arena",
                game_id: 999,
                created_by_user_id: 1,
                status: 'Open',
                team_size: 3,
                match_type: "Best of Three",
                region: "Test region",
                match_date: new Date().toISOString(),
                match_time: new Date().toISOString(),
                match_class: "Classic"
            }
        }
    ]
};

async function testWebhook() {
    console.log('Starting webhook connectivity test...\n');
    
    // 1. Basic URL validation
    try {
        new URL(config.webhookUrl);
        console.log('✅ URL format is valid');
    } catch (e) {
        console.error('❌ Invalid URL format:', config.webhookUrl);
        return;
    }

    // 2. Check if webhook secret is configured
    if (!config.webhookSecret) {
        console.error('❌ Webhook secret is not configured');
        return;
    } else {
        console.log('✅ Webhook secret is configured');
    }

    console.log('\nTesting endpoint connectivity...');
    console.log(`URL: ${config.webhookUrl}`);

    // 3. Test basic connectivity
    try {
        await axios.get(new URL(config.webhookUrl).origin);
        console.log('✅ Server is reachable');
    } catch (error) {
        if (error.code === 'ECONNREFUSED') {
            console.error('❌ Server is not reachable');
            console.error('Make sure your server is running and the domain/IP is correct');
            return;
        }
        // 404 is actually okay here as we're just testing connectivity
        console.log('✅ Server is reachable (responded with expected status)');
    }

    // 4. Run test cases
    console.log('\nRunning test cases...');
    
    for (const testCase of config.testCases) {
        console.log(`\nTest Case: ${testCase.name}`);
        console.log('Request Details:');
        console.log('- URL:', config.webhookUrl);
        console.log('- Method: POST');
        console.log('- Headers: Content-Type: application/json, x-webhook-token: [SECRET]');
        console.log('- Payload:', JSON.stringify(testCase.data, null, 2));

        try {
            const response = await axios.post(
                config.webhookUrl,
                testCase.data,
                {
                    headers: {
                        'Content-Type': 'application/json',
                        'x-webhook-token': config.webhookSecret
                    },
                    // Adding timeout and allowing self-signed certs for testing
                    timeout: 5000,
                    validateStatus: null,
                    httpsAgent: new (require('https').Agent)({  
                        rejectUnauthorized: false
                    })
                }
            );

            console.log('\nResponse:');
            console.log('Status:', response.status);
            console.log('Data:', JSON.stringify(response.data, null, 2));

            if (response.status >= 200 && response.status < 300) {
                console.log('✅ Test passed');
            } else {
                console.log('❌ Test failed');
                console.log('Unexpected status code:', response.status);
            }
        } catch (error) {
            console.log('❌ Test failed');
            if (error.response) {
                console.log('Status:', error.response.status);
                console.log('Response:', error.response.data);
            } else if (error.request) {
                console.log('No response received');
                console.log('Error:', error.message);
            } else {
                console.log('Error:', error.message);
            }
        }
    }
}

// Add proper error handling for the main function
testWebhook().catch(error => {
    console.error('Test failed with error:', error);
    process.exit(1);
});

// Add cleanup handler
process.on('SIGINT', () => {
    console.log('\nTest interrupted');
    process.exit(0);
});