<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Form\Type\Export;

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Regroupment;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Repository\RegroupmentRepository;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperForCurrentUserInterface;
use Chill\MainBundle\Service\Regroupement\RegroupementFiltering;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Pick centers amongst available centers for the user.
 */
final class PickCenterType extends AbstractType
{
    public function __construct(
        private readonly ExportManager $exportManager,
        private readonly RegroupmentRepository $regroupmentRepository,
        private readonly AuthorizationHelperForCurrentUserInterface $authorizationHelper,
        private readonly RegroupementFiltering $regroupementFiltering,
    ) {}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $export = $this->exportManager->getExport($options['export_alias']);
        $centers = $this->authorizationHelper->getReachableCenters(
            $export->requiredRole(),
        );

        $centersActive = array_filter($centers, fn (Center $c) => $c->getIsActive());

        // order alphabetically
        usort($centersActive, fn (Center $a, Center $b) => $a->getName() <=> $b->getName());

        $builder->add('centers', EntityType::class, [
            'class' => Center::class,
            'choices' => $centersActive,
            'label' => 'center',
            'multiple' => true,
            'expanded' => true,
            'choice_label' => static fn (Center $c) => $c->getName(),
        ]);

        $groups = $this->regroupementFiltering
            ->filterContainsAtLeastOneCenter($this->regroupmentRepository->findAllActive(), $centersActive);

        // order alphabetically
        usort($groups, fn (Regroupment $a, Regroupment $b) => $a->getName() <=> $b->getName());

        if (\count($groups) > 0) {
            $builder->add('regroupments', EntityType::class, [
                'class' => Regroupment::class,
                'label' => 'regroupment',
                'multiple' => true,
                'expanded' => true,
                'choices' => $groups,
                'choice_label' => static fn (Regroupment $r) => $r->getName(),
            ]);
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired('export_alias');
    }
}
