<?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\Form;

use CpCreation\AltchaBundle\Form\AltchaType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Site\Order\CheckoutType;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

final class CheckoutAltchaExclusionTest extends TestCase
{
    public function testCheckoutPublicFormContractHasNoAltchaTypeOrWidgetAttributes(): void
    {
        $addedTypes = [];
        $builder = $this->createMock(FormBuilderInterface::class);
        $builder
            ->method('add')
            ->willReturnCallback(static function (string $name, ?string $type = null) use (&$addedTypes, $builder): FormBuilderInterface {
                $addedTypes[$name] = $type;

                return $builder;
            })
        ;

        $reflection = new \ReflectionClass(CheckoutType::class);
        /** @var CheckoutType $checkoutType */
        $checkoutType = $reflection->newInstanceWithoutConstructor();
        $checkoutType->buildForm($builder, []);

        self::assertNotContains(AltchaType::class, $addedTypes);
        self::assertArrayNotHasKey('captcha', $addedTypes);

        $view = new FormView();
        $view->vars['attr'] = ['data-controller' => 'checkout'];
        $form = $this->createStub(FormInterface::class);
        $form->method('has')->willReturn(false);

        $checkoutType->finishView($view, $form, []);

        self::assertArrayNotHasKey(
            'data-cpcreation-altcha-challenge-url',
            $view->vars['attr'],
        );
        self::assertStringNotContainsString(
            'cpcreation-altcha',
            (string) ($view->vars['attr']['data-controller'] ?? ''),
        );
    }
}
