<?php declare(strict_types=1);

namespace Newland\NeosCommon\Routing;

use Neos\Neos\Domain\Model\Domain;
use Neos\Neos\Domain\Model\Site;
use Neos\Neos\Exception;
use Neos\Neos\Routing\Exception\NoSiteException;

class FrontendNodeRoutePartHandler extends \Neos\Neos\Routing\FrontendNodeRoutePartHandler
{
    /**
     * Returns a site matching the given $hostName
     *
     * @todo: This is lifted mostly from a future version of Neos. Refactor/replace after upgrade.
     */
    public function getSiteByHostName(?string $hostName): Site
    {
        if (!is_string($hostName)) {
            throw new NoSiteException(
                'Failed to determine current site because the "requestUriHost" Routing parameter is not set',
                1604860219
            );
        }

        /** @var ?Domain $domain */
        $domain = $this->domainRepository->findOneByHost($hostName, true);
        if ($domain !== null) {
            return $domain->getSite();
        }

        try {
            /** @var Site|null $defaultSite */
            $defaultSite = $this->siteRepository->findDefault();
            if ($defaultSite === null) {
                throw new NoSiteException(
                    'Failed to determine current site because no default site is configured',
                    1604929674
                );
            }
        } catch (Exception $exception) {
            throw new NoSiteException(
                sprintf(
                    'Failed to determine current site because no domain is specified matching host of "%s"' .
                    ' and no default site could be found: %s',
                    $hostName,
                    $exception->getMessage()
                ),
                1604860219,
                $exception
            );
        }
        return $defaultSite;
    }
}
