<?php

namespace MintyPHP\Module\Security\Providers;

use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\LayoutContextProvider;
use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Service\Access\AuthorizationService;

/**
 * Resolves the can_* navigation flags for the Security sidebar panel.
 *
 * Merged into $layoutNav under the 'security.nav' key and consumed by
 * templates/aside-security-panel.phtml.
 */
final class SecurityLayoutProvider implements LayoutContextProvider
{
    public function provide(array $session, AppContainer $container): array
    {
        $userId = (int) ($session['user']['id'] ?? 0);
        if ($userId <= 0) {
            return ['security.nav' => []];
        }

        try {
            $authorizationService = $container->get(AuthorizationService::class);
            $actorContext = ['actor_user_id' => $userId];
            $canViewChecks = $authorizationService->authorize(SecurityAuthorizationPolicy::ABILITY_CHECKS_VIEW, $actorContext)->isAllowed();
            $canManageTemplates = $authorizationService->authorize(SecurityAuthorizationPolicy::ABILITY_TEMPLATES_MANAGE, $actorContext)->isAllowed();
            $canManageSettings = $authorizationService->authorize(SecurityAuthorizationPolicy::ABILITY_SETTINGS_MANAGE, $actorContext)->isAllowed();
        } catch (\Throwable) {
            $canViewChecks = false;
            $canManageTemplates = false;
            $canManageSettings = false;
        }

        return ['security.nav' => [
            'can_view_checks' => $canViewChecks,
            'can_manage_templates' => $canManageTemplates,
            'can_manage_settings' => $canManageSettings,
        ]];
    }
}
