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

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickUserOrMeDynamicType;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

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

    public function __construct(private readonly UserRepositoryInterface $userRepository) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        if (!\in_array('acp_creator', $qb->getAllAliases(), true)) {
            $qb->join('acp.createdBy', 'acp_creator');
        }

        $qb
            ->andWhere($qb->expr()->in('acp_creator', ':creators'))
            ->setParameter('creators', $this->userOrMe($data['accepted_creators'], $exportGenerationContext));
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_creators', PickUserOrMeDynamicType::class, [
                'multiple' => true,
                'label' => false,
            ]);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'Filtered by creator: only %creators%', [
                '%creators%' => implode(
                    ', ',
                    array_map(
                        static fn (User $u) => $u->getLabel(),
                        $data['accepted_creators'] instanceof Collection ? $this->userOrMe($data['accepted_creators']->toArray(), $context) : $this->userOrMe($data['accepted_creators'], $context)
                    )
                ),
            ], ];
    }

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