<?php

namespace App\Security;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

#[AsEventListener(event: ResponseEvent::class, method: 'onResponse')]
class RedirecListener
{
    private bool $isDev;

    public function __construct(
    ) {
        // On considère être en dev si le mode debug de Symfony est activé
        $this->isDev = $_ENV['APP_ENV'] == "dev";
    }

    public function onResponse(ResponseEvent $event): void
    {
        $request = $event->getRequest();
        $host = $request->getHost();
        $pathInfo = $request->getPathInfo();

        // --- Logique Spécifique DEV / NGROK ---
        // Si on est en dev et que le host contient "ngrok-free.app" (ou "ngrok")
        if ($this->isDev && str_contains($host, 'ngrok') && !str_contains($pathInfo,'webhooks')) {
            // On redirige vers le domaine local esyweb.local en conservant le chemin et les paramètres
            $newUrl = "https://esyweb.local" . $pathInfo;
            $queryString = $request->getQueryString();
            if ($queryString) {
                $newUrl .= '?' . $queryString;
            }

            $redirect = new RedirectResponse($newUrl);
            $event->setResponse($redirect);
            $event->stopPropagation();
            return;
        }

        // --- Logique INTRANET ---
        if ($pathInfo === "/") {
            if ($host === "intranet.ludikevent.fr") {
                $redirect = new RedirectResponse("https://intranet.ludikevent.fr/intranet");
                $event->setResponse($redirect);
                $event->stopPropagation();
                return;
            }
        }

        if ($pathInfo === "/") {
            if ($host === "prestataire.ludikevent.fr") {
                $redirect = new RedirectResponse("https://prestataire.ludikevent.fr/etl");
                $event->setResponse($redirect);
                $event->stopPropagation();
                return;
            }
        }
    }
}
