<?php

namespace App\Tests\Security;

use App\Security\RedirecListener;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

#[AllowMockObjectsWithoutExpectations]
class RedirecListenerTest extends TestCase
{
    private $listener;

    protected function setUp(): void
    {
        // We need to control $_ENV['APP_ENV'] for the constructor logic
        $_ENV['APP_ENV'] = 'prod';
        $this->listener = new RedirecListener();
    }

    public function testIntranetRootRedirect()
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = Request::create('/');
        $request->headers->set('HOST', 'intranet.ludikevent.fr');
        $response = new Response();
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, $response);

        $this->listener->onResponse($event);

        $newResponse = $event->getResponse();
        $this->assertInstanceOf(RedirectResponse::class, $newResponse);
        $this->assertEquals('https://intranet.ludikevent.fr/intranet', $newResponse->getTargetUrl());
    }

    public function testReservationRedirect()
    {
        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = Request::create('/reservation/catalogue');
        $request->headers->set('HOST', 'reservation.ludikevent.fr');
        $response = new Response();
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, $response);

        $this->listener->onResponse($event);

        $newResponse = $event->getResponse();
        $this->assertInstanceOf(RedirectResponse::class, $newResponse);
        $this->assertEquals('https://reservation.ludikevent.fr/catalogue', $newResponse->getTargetUrl());
        $this->assertEquals(Response::HTTP_MOVED_PERMANENTLY, $newResponse->getStatusCode());
    }

    public function testDevNgrokRedirect()
    {
        $_ENV['APP_ENV'] = 'dev';
        $listener = new RedirecListener(); // Re-instantiate to pick up dev env

        $kernel = $this->createMock(HttpKernelInterface::class);
        $request = Request::create('/some/path?foo=bar');
        $request->headers->set('HOST', 'my-app.ngrok-free.app');
        $response = new Response();
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, $response);

        $listener->onResponse($event);

        $newResponse = $event->getResponse();
        $this->assertInstanceOf(RedirectResponse::class, $newResponse);
        $this->assertEquals('https://esyweb.local/some/path?foo=bar', $newResponse->getTargetUrl());
        
        $_ENV['APP_ENV'] = 'prod'; // Restore
    }
}
