<?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\Entity\AsideActivity;
use Chill\AsideActivityBundle\Export\Declarations;
use Chill\MainBundle\Entity\User\UserJobHistory;
use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Repository\UserJobRepositoryInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

class ByUserJobFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'aside_act_filter_user_job';

    public function __construct(
        private readonly TranslatableStringHelperInterface $translatableStringHelper,
        private readonly UserJobRepositoryInterface $userJobRepository,
    ) {}

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

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

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.AsideActivity::class." {$p}_act "
                    ."JOIN {$p}_act.agent {$p}_user "
                    .'JOIN '.UserJobHistory::class." {$p}_history WITH {$p}_history.user = {$p}_user "
                    ."WHERE {$p}_act = aside "
                    // job_at based on aside.date
                    ."AND {$p}_history.startDate <= aside.date "
                    ."AND ({$p}_history.endDate IS NULL OR {$p}_history.endDate > aside.date) "
                    ."AND {$p}_history.job IN ( :{$p}_jobs )"
                )
            )
            ->setParameter(
                "{$p}_jobs",
                $data['jobs'],
            );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('jobs', EntityType::class, [
                'class' => UserJob::class,
                'choices' => $this->userJobRepository->findAllActive(),
                'choice_label' => fn (UserJob $j) => $this->translatableStringHelper->localize($j->getLabel()),
                'multiple' => true,
                'expanded' => true,
            ]);
    }

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

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

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return ['export.filter.by_user_job.Filtered aside activities by user jobs: only %jobs%', [
            '%jobs%' => implode(
                ', ',
                array_map(
                    fn (UserJob $job) => $this->translatableStringHelper->localize($job->getLabel()),
                    $data['jobs'] instanceof Collection ? $data['jobs']->toArray() : $data['jobs']
                )
            ),
        ]];
    }

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

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