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

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;
    private const PREFIX = 'acpw_filter_creator';

    public function __construct(private UserRepositoryInterface $userRepository) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $p = self::PREFIX;

        $qb
            ->leftJoin('acpw.createdBy', "{$p}_creator")
            ->andWhere($qb->expr()->in("{$p}_creator", ":{$p}_creators"))
            ->setParameter("{$p}_creators", $this->userOrMe($data['creators'], $exportGenerationContext));
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('creators', PickUserOrMeDynamicType::class, [
                'multiple' => true,
                'label' => 'export.filter.work.by_creator.Creators',
            ]);
    }

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

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

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

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

    public function getFormDefaultData(): array
    {
        return [
            'creators' => [],
        ];
    }

    public function getTitle(): string
    {
        return 'export.filter.work.by_creator.title';
    }
}
