<?php

declare(strict_types=1);

namespace Flowaxy\Domain\Plugin\Services;

use Flowaxy\Contracts\Security\PluginCapabilityInterface;
use Flowaxy\Support\Facades\Log;
use Throwable;

// Менеджер capabilities плагінів
final class PluginCapabilityManager
{
    public function __construct(
        private readonly PluginCapabilityInterface $capabilityChecker
    ) {
    }

    public function checkCapabilitiesOnActivation(string $pluginSlug, array $declaredCapabilities): bool
    {
        if (empty($declaredCapabilities)) {
            return true;
        }

        foreach ($declaredCapabilities as $capability) {
            if (!$this->capabilityChecker->hasCapability($pluginSlug, $capability)) {
                try {
                    Log::Warning('Плагин требует capability, которая не предоставлена', [
                        'plugin_slug' => $pluginSlug,
                        'capability' => $capability,
                    ]);
                } catch (Throwable $e) {
                    // Ignore logging errors
                }
                return false;
            }
        }

        return true;
    }

    public function extractDeclaredCapabilities(array $pluginConfig): array
    {
        return $pluginConfig['capabilities'] ?? [];
    }
}
