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

use Chill\AsideActivityBundle\Export\Declarations;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickUserDynamicType;
use Chill\MainBundle\Templating\Entity\UserRender;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class ByUserFilter implements FilterInterface
{
    public function __construct(private readonly UserRender $userRender) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $clause = $qb->expr()->in('aside.agent', ':users');

        $qb
            ->andWhere($clause)
            ->setParameter('users', $data['accepted_users']);
    }

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

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

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

    public function describeAction($data, $format = 'string'): array
    {
        $users = [];

        foreach ($data['accepted_users'] as $u) {
            $users[] = $this->userRender->renderString($u, []);
        }

        return ['export.filter.Filtered aside activity by user: only %users%', [
            '%users%' => implode(', ', $users),
        ]];
    }

    public function getTitle(): string
    {
        return 'export.filter.Filter aside activity by user';
    }
}
