<?php

namespace App\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

#[AsEventListener(event: KernelEvents::REQUEST, priority: 256)]
class SubdomainRedirectListener
{
    private const SUBDOMAIN_ROUTES = [
        'webmail.e-cosplay.fr' => 'app_webmail_login',
        'status.e-cosplay.fr' => 'app_status',
    ];

    public function __construct(
        private UrlGeneratorInterface $urlGenerator,
    ) {
    }

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

        $request = $event->getRequest();
        $host = $request->getHost();

        if (!isset(self::SUBDOMAIN_ROUTES[$host])) {
            return;
        }

        $targetPath = $this->urlGenerator->generate(self::SUBDOMAIN_ROUTES[$host]);

        if ($request->getPathInfo() === $targetPath || str_starts_with($request->getPathInfo(), $targetPath.'/')) {
            return;
        }

        $event->setResponse(new RedirectResponse($targetPath, 302));
    }
}
