<?php

/*
 * This file is part of the Serenity 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 Serenity\CoreBundle\Shared\Form\Type\Common;

use Doctrine\ORM\EntityManagerInterface;
use Serenity\CoreBundle\Shared\Form\Loader\PaginatedChoiceLoader;
use Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class EntityPickerType extends AbstractType
{
    public function __construct(private readonly EntityManagerInterface $entityManager)
    {
    }

    public function getParent(): string
    {
        return EntityType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setRequired(['entity_class', 'repository']);
        $resolver->setDefaults([
            'limit' => 30,
            'class' => null,
            'offset' => 0,
            'selected' => [],
            'choice_label' => 'id',
            'multiple' => true,
            'expanded' => true,
            'by_reference' => false,
            'mapped' => true,
        ]);
        $resolver->setNormalizer('class', function ($options, $value) {
            return $options['entity_class'] ?? $value;
        });

        $resolver->setNormalizer('choice_loader', function ($options, $previous) {
            $repository = $options['repository'];
            $entityClass = $options['entity_class'];
            $selected = $options['selected'] ?? [];

            $paginatedLoader = new PaginatedChoiceLoader(
                $repository,
                $options['limit'],
                $options['offset'],
                $selected
            );

            return new DoctrineChoiceLoader(
                $this->entityManager,
                $entityClass,
                null,
                $paginatedLoader
            );
        });

        $resolver->setNormalizer('choice_attr', function ($options, $previous) {
            $repository = $options['repository'];
            $selected = $options['selected'] ?? [];

            $paginatedLoader = new PaginatedChoiceLoader(
                $repository,
                $options['limit'],
                $options['offset'],
                $selected
            );

            // ✅ liste des IDs de la page courante
            $idsInPage = [];
            foreach ($paginatedLoader->getPaginatedEntities() as $paginatedEntity) {
                $idsInPage[(string) $paginatedEntity->getId()] = true;
            }

            return static function ($entity) use ($idsInPage): array {
                return isset($idsInPage[(string) $entity->getId()])
                    ? []
                    : ['class' => 'hidden'];
            };
        });
    }
}
