<?php declare(strict_types=1);

namespace Newland\ToubizWidgetRendering\Service;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\ContentRepository\Domain\Service\ContextFactoryInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use Neos\Neos\Controller\Exception\NodeNotFoundException;
use Ramsey\Uuid\Uuid;

class WidgetPageService
{
    /**
     * @var array
     * @Flow\InjectConfiguration(path="redirect")
     */
    protected $configuration;
    /**
     * @var ContextFactoryInterface
     * @Flow\Inject
     */
    protected $contextFactory;

    public function getWidgetPageNode(string $language): NodeInterface
    {
        $nodeIdentifier = $this->configuration['node'];
        if (!$nodeIdentifier || !Uuid::isValid($nodeIdentifier)) {
            throw new InvalidConfigurationException(
                'Missing or invalid configuration for widget node. Check the setting' .
                ' `Newland.ToubizWidgetRendering.redirect.node`.'
            );
        }

        /** @var ?NodeInterface $node */
        $node = $this->contextFactory
            ->create(
                [
                    'dimensions' => [
                        'language' => [ $language ],
                    ],
                ]
            )
            ->getNodeByIdentifier($nodeIdentifier);

        if ($node === null) {
            throw new NodeNotFoundException(
                sprintf(
                    'No static widget page found for language "%s". Create one in the default language (if you' .
                    ' haven\'t done so already) and save a translated version of that one. Repeat this for' .
                    ' every language.',
                    $language
                )
            );
        }

        return $node;
    }
}
