<?php

declare(strict_types=1);

namespace apexl\Io\modules\menu\Factories;

use apexl\Io\exceptions\RouteNotFoundException;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\menu\includes\menuItem;
use apexl\Io\modules\user\exceptions\MasqueradeException;
use apexl\Io\modules\user\exceptions\PermissionException;
use apexl\Io\modules\user\services\CurrentUserFactory;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;

final readonly class MenuItemFactory
{
    public function __construct(private CurrentUserFactory $currentUserFactory, private Container $container, private RouteManager $routeManager) {}

    /**
     * @throws PermissionException
     * @throws NotFoundException
     * @throws MasqueradeException
     * @throws DependencyException
     */
    public function make(array $item): MenuItem
    {
        $path = '';
        $route = null;

        try {
            $route = $this->routeManager->getRoute($item['routeName']);
            $path = $this->routeManager->getRoutePattern($route->getName(), $item['replacements'] ?? []);
            if ($permission = unserialize($route->getArg('permission'))) {
                if (!$this->currentUserFactory->get()->isAllowed($permission)) {
                    throw new PermissionException('You do not have permission to access this page.');
                }
            }
        } catch (RouteNotFoundException) {
        }

        return $this->container->make(MenuItem::class, ['item' => $item, 'route' => $route, 'path' => $path]);
    }
}
