<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\AdminBundle\Menu;

use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use Serenity\AdminBundle\Event\ParamsAdminMenuEvent;
use Serenity\AdminBundle\Event\ParamsSuperAdminMenuEvent;
use Serenity\AdminBundle\Event\SidebarAdminMenuEvent;
use Serenity\AdminBundle\Event\SidebarSuperAdminMenuEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

final readonly class AdminBuilder
{
    public function __construct(
        private FactoryInterface $factory,
        private EventDispatcherInterface $eventDispatcher,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    public function sidebarMenu(): ItemInterface
    {
        $menu = $this->factory->createItem('root');
        $menu->addChild('dashboard', ['label' => 'Dashboard', 'route' => 'admin_index'])->setExtra('icon', 'icon-house');

        if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
            $menuSuperAdmin = $menu->addChild('super', ['label' => 'Super Admin'])->setExtra('icon', 'icon-shield-check');
            $this->eventDispatcher->dispatch(
                new SidebarSuperAdminMenuEvent($this->factory, $menuSuperAdmin)
            );
        }

        $this->eventDispatcher->dispatch(
            new SidebarAdminMenuEvent($this->factory, $menu)
        );

        return $menu;
    }

    public function paramsSuperAdminMenu(): ItemInterface
    {
        $menu = $this->factory->createItem('root');

        if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
            $this->eventDispatcher->dispatch(
                new ParamsSuperAdminMenuEvent($this->factory, $menu)
            );
        }

        return $menu;
    }

    public function paramsAdminMenu(): ItemInterface
    {
        $menu = $this->factory->createItem('root');

        if ($this->authorizationChecker->isGranted('ROLE_MODERATOR')) {
            $this->eventDispatcher->dispatch(
                new ParamsAdminMenuEvent($this->factory, $menu)
            );
        }

        return $menu;
    }
}
