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

final class PackagePolicyController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('updates.policy.view');
        $dashboard = (new PackagePolicyService())->dashboard();
        $this->view('platform/package_policy_center', [
            'pageTitle' => 'Package Policy Engine',
            'policyEnvironment' => (string)($dashboard['environment'] ?? 'local'),
            'packagePolicies' => (array)($dashboard['policies'] ?? []),
            'policyDecisions' => (array)($dashboard['decisions'] ?? []),
            'policyGeneratedAt' => (string)($dashboard['generated_at'] ?? ''),
        ]);
    }

    public function evaluate(): void
    {
        Auth::requireLogin();
        Permission::require('updates.policy.evaluate');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $result = (new PackagePolicyService())->evaluatePackageId((int)($_POST['package_id'] ?? 0), (int)(Auth::user()['id'] ?? 0) ?: null, true);
            $_SESSION[$result['decision'] === 'DENIED' ? 'error' : 'success'] = 'Package Policy : '.$result['decision'].' — '.$result['score'].'/100.';
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Évaluation impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/politiques-packages');
    }

    public function save(): void
    {
        Auth::requireLogin();
        Permission::require('updates.policy.manage');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            (new PackagePolicyService())->savePolicy($_POST, (int)(Auth::user()['id'] ?? 0) ?: null);
            $_SESSION['success'] = 'Politique enregistrée.';
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Enregistrement impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/politiques-packages');
    }

    public function toggle(): void
    {
        Auth::requireLogin();
        Permission::require('updates.policy.manage');
        Permission::requireSuperAdmin();
        Auth::requireRecentAuthentication();
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            (new PackagePolicyService())->togglePolicy((int)($_POST['policy_id'] ?? 0), (string)($_POST['active'] ?? '0') === '1', (int)(Auth::user()['id'] ?? 0) ?: null);
            $_SESSION['success'] = 'Statut de la politique mis à jour.';
        } catch (Throwable $e) {
            $_SESSION['error'] = 'Modification impossible : '.$e->getMessage();
        }
        $this->redirect('/administration/plateforme/politiques-packages');
    }
}
