const { spawn } = require('child_process');
const axios = require('axios');

console.log('🚀 Starting server...');

// Start the server
const server = spawn('node', ['server.js'], {
    stdio: 'pipe',
    cwd: __dirname
});

server.stdout.on('data', (data) => {
    console.log(`Server: ${data}`);
});

server.stderr.on('data', (data) => {
    console.error(`Server Error: ${data}`);
});

// Wait for server to start
setTimeout(async () => {
    try {
        console.log('🧪 Testing server...');
        
        // Test health endpoint
        const healthResponse = await axios.get('http://localhost:5500/health');
        console.log('✅ Health check passed:', healthResponse.data);
        
        // Test news categories
        const categoriesResponse = await axios.get('http://localhost:5500/api/news/categories');
        console.log('✅ Categories endpoint:', categoriesResponse.data);
        
        console.log('🎉 Server is working correctly!');
        
        // Kill the server
        server.kill();
        process.exit(0);
        
    } catch (error) {
        console.error('❌ Test failed:', error.message);
        if (error.response) {
            console.error('Response:', error.response.data);
        }
        server.kill();
        process.exit(1);
    }
}, 5000); // Wait 5 seconds for server to start
