<?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\RollbackTransactionManagerService;
use Throwable;

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

        $this->view('platform/rollback_transaction_manager', [
            'pageTitle' => 'Rollback Transaction Manager',
            'rollbackData' =>
                (new RollbackTransactionManagerService())->dashboard(),
        ]);
    }

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

        try {
            $result = (new RollbackTransactionManagerService())->execute(
                (int) ($_POST['package_id'] ?? 0),
                (string) ($_POST['confirmation'] ?? ''),
                (int) (Auth::user()['id'] ?? 0)
            );

            $_SESSION['success'] =
                (string) ($result['message'] ?? 'Rollback terminé.');
        } catch (Throwable $error) {
            $_SESSION['error'] =
                'Rollback interrompu : ' . $error->getMessage();
        }

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