<?php

namespace App\Tests\EventListener;

use App\EventListener\SubdomainRedirectListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SubdomainRedirectListenerTest extends TestCase
{
    private function createListener(): SubdomainRedirectListener
    {
        $urlGenerator = $this->createStub(UrlGeneratorInterface::class);
        $urlGenerator->method('generate')->willReturnMap([
            ['app_webmail_login', [], 1, '/webmail'],
            ['app_status', [], 1, '/status'],
        ]);

        return new SubdomainRedirectListener($urlGenerator);
    }

    private function createEvent(string $host, string $path = '/'): RequestEvent
    {
        $request = Request::create('https://'.$host.$path);
        $kernel = $this->createStub(HttpKernelInterface::class);

        return new RequestEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST);
    }

    public function testWebmailRedirect(): void
    {
        $event = $this->createEvent('webmail.e-cosplay.fr');
        ($this->createListener())($event);

        $this->assertInstanceOf(RedirectResponse::class, $event->getResponse());
        $this->assertSame('/webmail', $event->getResponse()->getTargetUrl());
    }

    public function testStatusRedirect(): void
    {
        $event = $this->createEvent('status.e-cosplay.fr');
        ($this->createListener())($event);

        $this->assertInstanceOf(RedirectResponse::class, $event->getResponse());
        $this->assertSame('/status', $event->getResponse()->getTargetUrl());
    }

    public function testNoRedirectOnCrmHost(): void
    {
        $event = $this->createEvent('crm.e-cosplay.fr');
        ($this->createListener())($event);

        $this->assertNull($event->getResponse());
    }

    public function testNoRedirectWhenAlreadyOnTarget(): void
    {
        $event = $this->createEvent('webmail.e-cosplay.fr', '/webmail');
        ($this->createListener())($event);

        $this->assertNull($event->getResponse());
    }

    public function testNoRedirectOnSubPath(): void
    {
        $event = $this->createEvent('status.e-cosplay.fr', '/status/api');
        ($this->createListener())($event);

        $this->assertNull($event->getResponse());
    }

    public function testSubRequestIgnored(): void
    {
        $request = Request::create('https://webmail.e-cosplay.fr/');
        $kernel = $this->createStub(HttpKernelInterface::class);
        $event = new RequestEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);

        ($this->createListener())($event);

        $this->assertNull($event->getResponse());
    }
}
