<?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\VitiCore\Bridge\Symfony\Bundle\Form\Site\ProductReviewReportType;
use CpCreation\VitiCore\Marketing\DTO\ProductReviewReportSubmission;
use CpCreation\VitiCore\Marketing\Model\ProductReviewReport;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Validator\Validation;

final class ProductReviewReportTypeTest extends TypeTestCase
{
    public function testItAcceptsAReasonAndAnOptionalComment(): void
    {
        $form = $this->factory->create(ProductReviewReportType::class);
        $form->submit([
            'reason' => ProductReviewReport::REASON_PERSONAL_DATA,
            'comment' => 'Une adresse postale est visible.',
        ]);

        self::assertTrue($form->isSynchronized());
        self::assertTrue($form->isValid());
        self::assertInstanceOf(ProductReviewReportSubmission::class, $form->getData());
        self::assertSame(ProductReviewReport::REASON_PERSONAL_DATA, $form->getData()->reason);
        self::assertSame('Une adresse postale est visible.', $form->getData()->comment);
    }

    public function testItRejectsAnUnknownReasonAndAnOversizedComment(): void
    {
        $form = $this->factory->create(ProductReviewReportType::class);
        $form->submit([
            'reason' => 'unknown',
            'comment' => str_repeat('a', 1001),
        ]);

        self::assertFalse($form->isValid());
        self::assertGreaterThan(0, $form->getErrors(true)->count());
    }

    protected function getExtensions(): array
    {
        $withoutCaptcha = new class extends AbstractTypeExtension {
            public function buildForm(FormBuilderInterface $builder, array $options): void
            {
                $builder->remove('captcha');
            }

            public static function getExtendedTypes(): iterable
            {
                yield ProductReviewReportType::class;
            }
        };

        return [
            new ValidatorExtension(
                Validation::createValidatorBuilder()->enableAttributeMapping()->getValidator()
            ),
            new PreloadedExtension([], [ProductReviewReportType::class => [$withoutCaptcha]]),
        ];
    }
}
