const express = require('express');
const path = require('path');
const SERVER_CONFIG = require('./server-config');
const DatabaseManager = require('./database/init');
const GameAPI = require('./api/game-api');

const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Initialize database and API
let db, gameAPI;

async function initializeServer() {
    try {
        // Initialize database
        db = new DatabaseManager();
        await db.initialize();
        
        // Initialize API
        gameAPI = new GameAPI(db);
        app.use('/api', gameAPI.router);
        
        console.log('Database and API initialized successfully');
        
    } catch (error) {
        console.error('Failed to initialize server:', error);
        process.exit(1);
    }
}

// Serve static files from public directory
app.use(express.static(SERVER_CONFIG.STATIC_PATH));

// Game routes
app.get('/game/:id', (req, res) => {
    res.sendFile(path.join(__dirname, SERVER_CONFIG.STATIC_PATH, 'index.html'));
});

// Route for root path
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, SERVER_CONFIG.STATIC_PATH, 'index.html'));
});

// Health check endpoint
app.get('/health', (req, res) => {
    res.json({ 
        status: 'healthy', 
        timestamp: new Date().toISOString(),
        database: db ? 'connected' : 'disconnected'
    });
});

// Error handling middleware
app.use((error, req, res, next) => {
    console.error('Server error:', error);
    res.status(500).json({ error: 'Internal server error' });
});

// Graceful shutdown
process.on('SIGINT', async () => {
    console.log('\nShutting down server...');
    if (db) {
        await db.close();
    }
    process.exit(0);
});

// Start server
async function startServer() {
    await initializeServer();
    
    app.listen(SERVER_CONFIG.PORT, SERVER_CONFIG.HOST, () => {
        console.log(`Grid Battle Game server running at http://${SERVER_CONFIG.HOST}:${SERVER_CONFIG.PORT}`);
        console.log('API endpoints available at /api/*');
        console.log('Health check: /health');
        console.log('Open your browser and navigate to the URL above to play!');
    });
}

startServer().catch(error => {
    console.error('Failed to start server:', error);
    process.exit(1);
});

module.exports = app;