<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Tests\Controller;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site\LocaleController;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Provider\LocaleProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Routing\RouterInterface;

final class LocaleControllerTest extends TestCase
{
    public function testItRedirectsOnlyToASameOriginRefererAndPreservesItsQuery(): void
    {
        [$controller, $request, $session] = $this->createController(
            'https://example.test/contact?tag=one&tag=two',
        );

        $response = $controller->setLocale($request, 'en');

        self::assertSame('/contact?tag=one&tag=two', $response->getTargetUrl());
        self::assertSame('en', $session->get('_locale'));
    }

    public function testItRejectsAnExternalReferer(): void
    {
        [$controller, $request, $session] = $this->createController(
            'https://example.invalid/phishing',
        );

        $response = $controller->setLocale($request, 'en');

        self::assertSame('/', $response->getTargetUrl());
        self::assertSame('en', $session->get('_locale'));
    }

    public function testItDoesNotStoreAnUnsupportedLocale(): void
    {
        [$controller, $request, $session] = $this->createController(null);

        $response = $controller->setLocale($request, 'zz');

        self::assertSame('/', $response->getTargetUrl());
        self::assertFalse($session->has('_locale'));
    }

    /** @return array{LocaleController, Request, Session} */
    private function createController(?string $referer): array
    {
        $request = Request::create('https://example.test/request/locale/en');
        if (null !== $referer) {
            $request->headers->set('referer', $referer);
        }

        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);
        $requestStack = new RequestStack();
        $requestStack->push($request);

        $router = $this->createMock(RouterInterface::class);
        $router->method('generate')->with('homepage')->willReturn('/');
        $localeProvider = $this->createMock(LocaleProvider::class);
        $localeProvider->method('getLocales')->willReturn(['fr', 'en']);

        return [new LocaleController($router, $requestStack, $localeProvider), $request, $session];
    }
}
