<?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\Offer;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\AdminBundle\Form\AsOfferFormType;
use Ferienpass\CoreBundle\Entity\Host;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Count;

#[AsOfferFormType]
class Hosts extends AbstractType
{
    public function __construct(private readonly Security $security)
    {
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $user = $this->security->getUser();

        $resolver->setDefaults([
            'section' => 'default',
            'required' => true,
            'class' => Host::class,
            'query_builder' => function (EntityRepository $er) use ($user): QueryBuilder {
                $qb = $er->createQueryBuilder('h');

                if (!$this->security->isGranted('ROLE_ADMIN')) {
                    $qb->innerJoin('h.memberAssociations', 'm', Join::WITH, 'm.user = :user')->setParameter('user', $user);
                }

                return $qb->orderBy('h.name');
            },
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => false,
            'help' => 'offers.help.hosts',
            'autocomplete' => true,
            'constraints' => [new Count(min: 1)],
        ]);
    }

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