<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\EventSubscriber;

use Mautic\CoreBundle\CoreEvents;
use Mautic\CoreBundle\Event\MenuEvent;
use MauticPlugin\DealFlowBundle\Service\LicenseService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Removes Deal Flow menu items when the plugin is not licensed.
 * Listens at a very late priority so the menu items are already built by CoreSubscriber.
 */
final class LicenseMenuSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly LicenseService $licenseService,
    ) {
    }

    /**
     * @return array<string, array<int, int|string>>
     */
    public static function getSubscribedEvents(): array
    {
        return [
            CoreEvents::BUILD_MENU => ['onBuildMenu', -1000],
        ];
    }

    public function onBuildMenu(MenuEvent $event): void
    {
        if ($event->getType() !== 'main') {
            return;
        }

        if ($this->licenseService->isLicensed()) {
            return;
        }

        // Access the internal menu items array directly and remove the Deal Flow root.
        // MenuEvent stores items at $menuItems['children']['dealflow.menu.root'].
        // We use setMenuItems to replace the full array with the root item removed.
        $reflection = new \ReflectionProperty(MenuEvent::class, 'menuItems');
        /** @var array<string, mixed> $menuItems */
        $menuItems = $reflection->getValue($event);

        if (isset($menuItems['children']['dealflow.menu.root'])) {
            unset($menuItems['children']['dealflow.menu.root']);
            $event->setMenuItems($menuItems);
        }
    }
}
