<?php declare(strict_types=1);

namespace Newland\NeosCommon\LinkHandler;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Aop\JoinPointInterface;
use Newland\NeosCommon\Service\ControllerContextFactory;
use function Safe\preg_match;

/**
 * Aspect that extends Neos' shortcut resolution to also support record uris.
 * This allows users to choose a record as a shortcut target in the backend.
 *
 * @Flow\Aspect()
 */
class LinkHandlerShortcutResolver
{

    /**
     * @var LinkingService
     * @Flow\Inject()
     */
    protected $linkingService;

    /**
     * @var ControllerContextFactory
     * @Flow\Inject()
     */
    protected $controllerContextFactory;

    /**
     * @Flow\Around("method(Neos\Neos\Domain\Service\NodeShortcutResolver->resolveShortcutTarget())")
     * @param JoinPointInterface $joinPoint
     * @return mixed
     */
    public function resolveShortcutTarget(JoinPointInterface $joinPoint)
    {
        /** @var Node $node */
        $node = $joinPoint->getMethodArgument('node');

        return $this->resolveRecordShortcut($node)
            ?? $joinPoint->getAdviceChain()->proceed($joinPoint);
    }

    private function resolveRecordShortcut(Node $node): ?string
    {
        $target = $node->getProperty('target');
        if (!$target) {
            return null;
        }

        $target = $this->linkingService->nodeUriWorkaround($target);
        if (!preg_match('/^record:\/\//', $target)) {
            return null;
        }

        return $this->linkingService->resolveRecordUri(
            $target,
            $node,
            $this->controllerContextFactory->initializeFakeControllerContext($node),
            true
        );
    }
}
