<?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\Admin\SecurityController;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

final class AdminSecurityControllerTest extends TestCase
{
    public function testStoredAdminTargetPathIsPreservedForLogin(): void
    {
        $request = new Request();
        $session = new Session(new MockArraySessionStorage());
        $session->set(
            '_security.admin.target_path',
            'https://example.test/admincp/marketing/avis-produits/review-id?intent=reject#review-reject',
        );
        $request->setSession($session);

        $reflection = new \ReflectionClass(SecurityController::class);
        $controller = $reflection->newInstanceWithoutConstructor();
        $resolveTargetPath = $reflection->getMethod('resolveTargetPath');

        self::assertSame(
            'https://example.test/admincp/marketing/avis-produits/review-id?intent=reject#review-reject',
            $resolveTargetPath->invoke($controller, $request),
        );
    }

    public function testLoginTemplatePostsStoredTargetPath(): void
    {
        $template = file_get_contents(
            __DIR__.'/../../src/Bridge/Symfony/Bundle/Resources/views/admin/login.html.twig',
        );

        self::assertIsString($template);
        self::assertStringContainsString('name="_target_path" value="{{ target_path }}"', $template);
    }

    public function testAdminLoginRequiresTheSameCsrfTokenAsItsTemplate(): void
    {
        $template = file_get_contents(
            __DIR__.'/../../src/Bridge/Symfony/Bundle/Resources/views/admin/login.html.twig',
        );
        $security = file_get_contents(
            __DIR__.'/../../src/Bridge/Symfony/Bundle/Resources/config/packages/security.yaml',
        );

        self::assertIsString($template);
        self::assertIsString($security);
        self::assertStringContainsString('name="_csrf_token" value="{{ csrf_token(\'authenticate\') }}"', $template);
        self::assertStringContainsString('enable_csrf: true', $security);
        self::assertStringContainsString("csrf_parameter: '_csrf_token'", $security);
        self::assertStringContainsString("csrf_token_id: 'authenticate'", $security);
    }
}
