import pool from '../db.js';
import { getSectorSettings } from '../services/config.service.js';

/**
 * Gibt den Status, die Live-Statistiken und die Konfiguration des Sektor-Backends zurück.
 * Wird alle 30 Sekunden vom Heartbeat-Service der Lobby aufgerufen.
 * 
 * @param {import('express').Request} req - Das Express Request-Objekt
 * @param {import('express').Response} res - Das Express Response-Objekt
 */
export const getHealthStatus = async (req, res) => {
    try {
        const settings = getSectorSettings();
        
        const onlineResult = await pool.query(`
            SELECT COUNT(*) FROM local_accounts 
            WHERE updated_at > NOW() - INTERVAL '60 minutes'
        `);

        const totalPlayersResult = await pool.query('SELECT COUNT(*) FROM local_accounts');
        
        const planetsResult = await pool.query('SELECT COUNT(*) FROM planets');

        return res.status(200).json({ 
            status: 'ok',
            timestamp: new Date().toISOString(),
            stats: {
                online_players: parseInt(onlineResult.rows[0].count, 10),
                total_players: parseInt(totalPlayersResult.rows[0].count, 10),
                planets_count: parseInt(planetsResult.rows[0].count, 10)
            },
            config: {
                max_galaxies: settings.universe_dimensions.max_galaxies,
                speed_economy: settings.game_speeds.economy_speed,
                research_speed: settings.game_speeds.research_speed,
                fleet_speed_hostile: settings.game_speeds.fleet_speed_hostile,
                fleet_speed_peaceful: settings.game_speeds.fleet_speed_peaceful,
                fleet_speed_friendly: settings.game_speeds.fleet_speed_friendly,
                fuel_consumption_factor: settings.game_speeds.fuel_consumption_factor,
                fleet_to_debris_percentage: settings.debris_fields.fleet_to_debris_percentage,
                defense_to_debris_percentage: settings.debris_fields.defense_to_debris_percentage,
                fuel_included_in_debris: settings.debris_fields.fuel_included_in_debris,
                initial_res_premium: settings.account_registration_bonus.initial_res_premium,
                bonus_fields: settings.planet_generation.bonus_fields
            }
        });

    } catch (error) {
        console.error('❌ Fehler im Health-Controller:', error);
        return res.status(500).json({ status: 'error', message: 'Internal Server Error' });
    }
};