<?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\PackageManager\PackageRepairService; use Throwable;
final class PackageRepairController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin(); Permission::require('packages.repair');
        $service=new PackageRepairService();
        $this->view('platform/package_repair',['pageTitle'=>'Repair & Recovery Engine','repairPackages'=>$service->packages(),'repairDiagnostics'=>$service->latestDiagnostics()]);
    }
    public function diagnose(): void
    {
        Auth::requireLogin(); Permission::require('packages.repair'); Permission::requireSuperAdmin(); Auth::requireRecentAuthentication(); Csrf::verify($_POST['_csrf']??null);
        try { $r=(new PackageRepairService())->diagnose((int)($_POST['registry_id']??0),(int)(Auth::user()['id']??0)?:null); $_SESSION['success']='Diagnostic terminé : '.$r['state'].' · '.$r['score'].'/100.'; }
        catch(Throwable $e){$_SESSION['error']='Diagnostic impossible : '.$e->getMessage();}
        $this->redirect('/administration/plateforme/packages/reparation');
    }
    public function repair(): void
    {
        Auth::requireLogin(); Permission::require('packages.repair'); Permission::requireSuperAdmin(); Auth::requireRecentAuthentication(); Csrf::verify($_POST['_csrf']??null);
        try { $simulate=(string)($_POST['mode']??'simulate')!=='repair'; $r=(new PackageRepairService())->repair((int)($_POST['registry_id']??0),$simulate,(int)(Auth::user()['id']??0)?:null); $_SESSION['success']=$simulate?'Simulation terminée : '.count($r['targets']).' fichier(s) à restaurer.':'Réparation terminée : '.$r['repaired'].' fichier(s) restauré(s).'; }
        catch(Throwable $e){$_SESSION['error']='Réparation interrompue : '.$e->getMessage();}
        $this->redirect('/administration/plateforme/packages/reparation');
    }
}
