<?php

declare(strict_types=1);

namespace App\EventSubscriber;

use App\Service\Tenant\TenantResolver;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class CanonicalTenantDomainSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly TenantResolver $tenantResolver,
        private readonly string $scheme = 'https',
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['redirectAliasToCanonicalHost', 32],
        ];
    }

    public function redirectAliasToCanonicalHost(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();
        $canonicalHost = $this->tenantResolver->canonicalRedirectHost($request);
        if ($canonicalHost === null) {
            return;
        }

        $event->setResponse(new RedirectResponse(
            sprintf('%s://%s%s', trim($this->scheme) ?: $request->getScheme(), $canonicalHost, $request->getRequestUri()),
            RedirectResponse::HTTP_MOVED_PERMANENTLY
        ));
    }
}
