<?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\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\TranslatableStringHelper;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class JobFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'cal_filter_job';

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

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

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

        $qb
            ->leftJoin('cal.mainUser', "{$p}_user")
            ->leftJoin(
                UserJobHistory::class,
                "{$p}_history",
                Join::WITH,
                $qb->expr()->eq("{$p}_history.user", "{$p}_user")
            )
            // job_at based on cal.startDate
            ->andWhere(
                $qb->expr()->andX(
                    $qb->expr()->lte("{$p}_history.startDate", 'cal.startDate'),
                    $qb->expr()->orX(
                        $qb->expr()->isNull("{$p}_history.endDate"),
                        $qb->expr()->gt("{$p}_history.endDate", 'cal.startDate')
                    )
                )
            )
            ->andWhere($qb->expr()->in("{$p}_history.job", ":{$p}_job"))
            ->setParameter(
                "{$p}_job",
                $data['job']
            );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('job', 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 ['job' => $this->normalizeDoctrineEntity($formData['job'])];
    }

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

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

        foreach ($data['job'] as $j) {
            $userJobs[] = $this->translatableStringHelper->localize(
                $j->getLabel()
            );
        }

        return ['export.filter.calendar.agent_job.Filtered by agent job: only %jobs%', [
            '%jobs%' => implode(', ', $userJobs),
        ]];
    }

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

    public function getTitle(): string
    {
        return 'export.filter.calendar.agent_job.Filter calendars by agent job';
    }
}
