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

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

        $service = new DependencyResolverService();
        $focusedPackageId = isset($_GET['package_id'])
            ? (int) $_GET['package_id']
            : null;

        $dashboard = $service->dashboard($focusedPackageId);

        $this->view('platform/package_dependencies', [
            'pageTitle' => 'Dependency Graph PRO',
            'dependencyData' => $dashboard,
        ]);
    }

    public function analyze(): void
    {
        Auth::requireLogin();
        Permission::require('packages.dependencies.manage');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);

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

        try {
            $result = (new DependencyResolverService())->analyze(
                $packageId,
                (int) (Auth::user()['id'] ?? 0) ?: null
            );

            $_SESSION['success'] =
                'Analyse terminée : '
                . $result['decision']
                . ' · '
                . $result['score']
                . '/100.';
        } catch (Throwable $error) {
            $_SESSION['error'] =
                'Analyse impossible : ' . $error->getMessage();
        }

        $this->redirect(
            '/administration/plateforme/packages/dependances'
            . ($packageId > 0 ? '?package_id=' . $packageId : '')
        );
    }
}
