<?php

namespace Velis\Mvc\View\Helper;

use Velis\App;
use Velis\Exception as VelisException;
use Velis\Mvc\FrontendRouting;
use Velis\Mvc\Router;
use Velis\Mvc\View;

class SwitchableUrl
{
    /**
     * Returns new frontend url if module is switched, vintage url (by ini routing) if not
     * Use for regular links that should point to React interface when module is switched
     * Pass $frontendPath as the last argument if a given route is not defined in ini with "frontend-" prefix
     */
    public function __invoke(string $routeName, string $switchableModule, ?string $frontendPath = null): string
    {
        /** @var View $view */
        $view = App::getService('view');

        /** @var Router|\Phalcon\Mvc\Router $currentRouter */
        $currentRouter = App::getService('router');

        if ($currentRouter instanceof Router && $currentRouter->isModuleSwitched($switchableModule)) {
            if ($frontendPath) {
                return $frontendPath;
            }

            try {
                return $view->url((string) FrontendRouting::FRONTEND_ROUTE_PREFIX . $routeName);
            } catch (\Exception $e) {
                VelisException::raise("No frontend-route found for route name $routeName");
                return $view->url($routeName);
            }
        }

        return $view->url($routeName);
    }
}
