<?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\CalendarBundle\Export\Filter;

use Chill\CalendarBundle\Export\Declarations;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class AgentFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(private UserRender $userRender, private UserRepositoryInterface $userRepository) {}

    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $where = $qb->getDQLPart('where');
        $clause = $qb->expr()->in('cal.mainUser', ':agents');

        if ($where instanceof Andx) {
            $where->add($clause);
        } else {
            $where = $qb->expr()->andX($clause);
        }

        $qb->add('where', $where);
        $qb->setParameter('agents', $data['accepted_agents']);
    }

    public function applyOn(): string
    {
        return Declarations::CALENDAR_TYPE;
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('accepted_agents', EntityType::class, [
            'class' => User::class,
            'choice_label' => fn (User $u) => $this->userRender->renderString($u, []),
            'multiple' => true,
            'expanded' => true,
        ]);
    }

    public function getNormalizationVersion(): int
    {
        return 1;
    }

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_agents' => $this->normalizeDoctrineEntity($formData['accepted_agents'])];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_agents' => $this->denormalizeDoctrineEntity($formData['accepted_agents'], $this->userRepository)];
    }

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $users = [];

        foreach ($data['accepted_agents'] as $r) {
            $users[] = $r;
        }

        return [
            'Filtered by agent: only %agents%', [
                '%agents' => implode(', ', $users),
            ], ];
    }

    public function getTitle(): string
    {
        return 'Filter calendars by agent';
    }
}
