<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Permission;
use App\Core\Health\SystemHealth;
use App\Core\Migrations\MigrationManager;
use App\Core\Modules\ModuleManager;
use App\Services\AuditSummaryService;
use App\Services\BackupInventoryService;
use App\Services\DatabaseHealthService;
use App\Services\RuntimeEnvironmentService;
use App\Services\SystemConsistencyService;
use App\Services\SystemIntegrityService;

final class CoreSystemController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('axiom.kernel.view');

        $moduleConfig = require BASE_PATH . '/config/modules.php';
        $moduleManager = new ModuleManager(
            $moduleConfig['paths'] ?? [BASE_PATH . '/modules'],
            $moduleConfig['manifest'] ?? 'module.json'
        );
        $migrationManager = new MigrationManager(BASE_PATH . '/database/migrations');
        $health = new SystemHealth($moduleManager, $migrationManager, BASE_PATH . '/storage');

        $this->view('axiom_core/system', [
            'pageTitle' => 'AXIOM Core — Console administrateur',
            'coreVersion' => is_file(BASE_PATH . '/CORE_VERSION') ? trim((string)file_get_contents(BASE_PATH . '/CORE_VERSION')) : 'inconnue',
            'appVersion' => is_file(BASE_PATH . '/VERSION') ? trim((string)file_get_contents(BASE_PATH . '/VERSION')) : 'inconnue',
            'checks' => $health->report(),
            'modules' => $moduleManager->discover(),
            'migrations' => $migrationManager->status(),
            'integrity' => (new SystemIntegrityService())->report(),
            'databaseHealth' => (new DatabaseHealthService())->report(),
            'runtime' => (new RuntimeEnvironmentService())->report(),
            'backups' => (new BackupInventoryService())->report(),
            'audit' => (new AuditSummaryService())->report(),
            'consistency' => (new SystemConsistencyService())->report(),
        ]);
    }
}
