<?php

declare(strict_types=1);

namespace CpCreation\AltchaBundle\Form;

use CpCreation\AltchaBundle\Security\ProtectionState;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraint;

final class AltchaValidationGroupsExtension extends AbstractTypeExtension
{
    public function __construct(private readonly ProtectionState $state)
    {
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setNormalizer('validation_groups', function (Options $options, mixed $groups): \Closure {
            return function (FormInterface $form) use ($groups): mixed {
                if ($this->state->isRejected($form)) {
                    return [];
                }

                if (is_callable($groups)) {
                    return $groups($form);
                }

                return null === $groups ? [Constraint::DEFAULT_GROUP] : $groups;
            };
        });
    }

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