<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Form\Filter\Consent;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\AdminBundle\Form\Filter\AbstractFilterType;
use Ferienpass\AdminBundle\Form\Filter\AsSubFilter;
use Ferienpass\CoreBundle\Entity\ConsentForm;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
 * Filter signatures by the consent form they belong to. Also the target of
 * the consent editors' lockbar deep link ("X Personen haben unterschrieben"),
 * which passes all consent-form uuids of an offer/edition.
 */
#[AsSubFilter(key: 'consentForm', section: 'base', priority: 70, views: ['admin_consents_index'])]
class FormFilter extends AbstractFilterType
{
    public function getParent(): string
    {
        return EntityType::class;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'class' => ConsentForm::class,
            'query_builder' => static fn (EntityRepository $er): QueryBuilder => $er->createQueryBuilder('f')
                ->leftJoin('f.offer', 'o')
                ->leftJoin('f.edition', 'e')
                ->addSelect('o', 'e')
                ->orderBy('f.title'),
            'choice_value' => static fn (?ConsentForm $form) => $form?->getId()->toRfc4122(),
            'choice_label' => static fn (ConsentForm $form): string => self::label($form),
            'placeholder' => '-',
            'multiple' => true,
        ]);
    }

    public function apply(QueryBuilder $qb, FormInterface $form): void
    {
        if ($form->isEmpty()) {
            return;
        }

        $forms = $form->getData();
        if (0 === \count($forms)) {
            return;
        }

        // Bind the binary uuid values explicitly: Doctrine stringifies entities
        // in array parameters to their rfc4122 form, which never matches the
        // BINARY(16) id column.
        $k = $form->getName();
        $qb->andWhere('i.consentForm IN (:q_'.$k.')')
            ->setParameter('q_'.$k, array_map(static fn (ConsentForm $f) => $f->getId()->toBinary(), iterator_to_array($forms)));
    }

    protected function getHumanReadableValue(FormInterface $form): string|TranslatableInterface|null
    {
        $forms = $form->getData();
        if (null === $forms || 0 === \count($forms)) {
            return null;
        }

        return implode(', ', array_map(static fn (ConsentForm $f): string => self::label($f), iterator_to_array($forms)));
    }

    private static function label(ConsentForm $form): string
    {
        $scope = $form->getOffer()?->getName() ?? $form->getEdition()?->getName();

        return ($form->getTitle() ?: '—').($scope ? ' · '.$scope : '');
    }
}
