/**
 * Debug Dashboard Issue
 * Run with: node debug-dashboard.js
 */

const http = require('http');

console.log('\n🔍 Debugging Dashboard Issue\n');
console.log('='.repeat(60));

// Test 1: Check if server is running
function testServerRunning() {
    return new Promise((resolve) => {
        const req = http.get('http://localhost:5000/', (res) => {
            console.log('✅ Server is running');
            console.log('   Status Code:', res.statusCode);
            resolve(true);
        });

        req.on('error', (error) => {
            console.log('❌ Server is NOT running');
            console.log('   Error:', error.message);
            console.log('\n   Start server with: npm run dev\n');
            resolve(false);
        });

        req.setTimeout(5000, () => {
            req.destroy();
            console.log('❌ Server timeout - server may not be running');
            resolve(false);
        });
    });
}

// Test 2: Check dashboard HTML endpoint
function testDashboardHTML() {
    return new Promise((resolve) => {
        console.log('\n📄 Testing Dashboard HTML endpoint:');

        const req = http.get('http://localhost:5000/user-dashboard', (res) => {
            console.log('   Status Code:', res.statusCode);

            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                if (res.statusCode === 200) {
                    console.log('   ✅ Dashboard HTML loads successfully');
                } else {
                    console.log('   ❌ Dashboard HTML failed');
                    console.log('   Response:', data.substring(0, 200));
                }
                resolve();
            });
        });

        req.on('error', (error) => {
            console.log('   ❌ Error:', error.message);
            resolve();
        });

        req.setTimeout(5000, () => {
            req.destroy();
            console.log('   ❌ Request timeout');
            resolve();
        });
    });
}

// Test 3: Check API endpoint (without auth)
function testDashboardAPI() {
    return new Promise((resolve) => {
        console.log('\n🔌 Testing Dashboard API endpoint (no auth):');

        const req = http.get('http://localhost:5000/api/user/dashboard', (res) => {
            console.log('   Status Code:', res.statusCode);

            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                try {
                    const json = JSON.parse(data);
                    console.log('   Response:', JSON.stringify(json, null, 2));

                    if (json.error === 'Endpoint not found') {
                        console.log('\n   ❌ ISSUE FOUND: Endpoint not found error');
                        console.log('   This means the route is not registered properly');
                    } else if (json.error === 'Access token required') {
                        console.log('   ✅ Endpoint exists! (Auth required - this is expected)');
                    }
                } catch (e) {
                    console.log('   Response (raw):', data.substring(0, 200));
                }
                resolve();
            });
        });

        req.on('error', (error) => {
            console.log('   ❌ Error:', error.message);
            resolve();
        });

        req.setTimeout(5000, () => {
            req.destroy();
            console.log('   ❌ Request timeout');
            resolve();
        });
    });
}

// Test 4: List all routes
function checkServerFile() {
    console.log('\n📋 Checking server.js routes:');

    const fs = require('fs');
    const serverContent = fs.readFileSync('./server.js', 'utf8');

    // Check if dashboard route exists
    if (serverContent.includes("app.get('/api/user/dashboard'")) {
        console.log('   ✅ Dashboard route defined in server.js');
    } else {
        console.log('   ❌ Dashboard route NOT found in server.js');
    }

    // Check 404 handler position
    const lines = serverContent.split('\n');
    let dashboardLine = -1;
    let notFoundLine = -1;

    lines.forEach((line, index) => {
        if (line.includes("app.get('/api/user/dashboard'")) {
            dashboardLine = index + 1;
        }
        if (line.includes("404 handler")) {
            notFoundLine = index + 1;
        }
    });

    if (dashboardLine > 0 && notFoundLine > 0) {
        console.log('   Dashboard route at line:', dashboardLine);
        console.log('   404 handler at line:', notFoundLine);

        if (dashboardLine < notFoundLine) {
            console.log('   ✅ Route is before 404 handler (correct order)');
        } else {
            console.log('   ❌ Route is AFTER 404 handler (wrong order!)');
        }
    }
}

// Run all tests
async function runAllTests() {
    console.log('\n🚀 Running Dashboard Diagnostics...\n');

    const serverRunning = await testServerRunning();

    if (!serverRunning) {
        console.log('\n' + '='.repeat(60));
        console.log('⚠️  Server must be running to complete tests');
        console.log('   Start with: cd /mnt/c/xampp/htdocs/waka_traffic && npm run dev');
        console.log('='.repeat(60) + '\n');
        return;
    }

    await testDashboardHTML();
    await testDashboardAPI();
    checkServerFile();

    console.log('\n' + '='.repeat(60));
    console.log('✅ Diagnostics Complete\n');
}

runAllTests();
