<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Services\UpdateValidationEngineService;
use Throwable;

final class UpdateValidationEngineController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.view');

        $this->view('platform/update_validation_center', [
            'pageTitle' => 'Enterprise Validation Center',
            'data' => (new UpdateValidationEngineService())->dashboard(),
        ]);
    }

    public function simulate(): void
    {
        Auth::requireLogin();
        Permission::require('updates.validation.simulate');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);

        try {
            $packageId = (int) ($_POST['package_id'] ?? 0);

            $result = (new UpdateValidationEngineService())->simulate(
                $packageId,
                (int) (Auth::user()['id'] ?? 0) ?: null
            );

            $_SESSION[$result['ok'] ? 'success' : 'error'] =
                $result['ok']
                    ? 'Simulation réussie : aucune écriture effectuée.'
                    : 'Simulation bloquée : consultez le rapport.';
        } catch (Throwable $error) {
            $_SESSION['error'] = 'Simulation impossible : ' . $error->getMessage();
        }

        $this->redirect('/administration/plateforme/validation');
    }
}
