<?php
// api/health.php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../lib/Logger.php';
require_once __DIR__ . '/../lib/Monitor.php';

$config = require __DIR__ . '/../config.php';

try {
    $pdo = new PDO(
        "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
        $config['db_user'],
        $config['db_pass'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    
    $monitor = new Monitor($pdo);
    $health = $monitor->checkSystemHealth();
    
    // Общий статус системы
    $overall_status = 'healthy';
    foreach ($health as $check) {
        if (is_array($check) && isset($check['status']) && $check['status'] === 'error') {
            $overall_status = 'degraded';
            break;
        }
    }
    
    echo json_encode([
        'status' => $overall_status,
        'timestamp' => date('c'),
        'checks' => $health
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    Logger::error('Health check failed', ['error' => $e->getMessage()]);
    echo json_encode(['status' => 'error', 'message' => 'Health check failed']);
}
?>