<?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\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 Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Translation\TranslatableMessage;

final readonly class CreatorJobFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'acp_filter_creator_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
            ->join(
                'acp.userHistories',
                "{$p}_userHistory",
                Join::WITH,
                $qb->expr()->andX(
                    $qb->expr()->eq("{$p}_userHistory.accompanyingPeriod", 'acp.id'),
                    $qb->expr()->andX(
                        $qb->expr()->gte('COALESCE(acp.closingDate, CURRENT_TIMESTAMP())', "{$p}_userHistory.startDate"),
                        $qb->expr()->orX(
                            $qb->expr()->isNull("{$p}_userHistory.endDate"),
                            $qb->expr()->lt('COALESCE(acp.closingDate, CURRENT_TIMESTAMP())', "{$p}_userHistory.endDate")
                        )
                    )
                )
            )
            ->leftJoin(
                UserJobHistory::class,
                "{$p}_history",
                Join::WITH,
                $qb->expr()->andX(
                    $qb->expr()->eq("{$p}_history.user", "{$p}_userHistory.createdBy"),
                    $qb->expr()->andX(
                        $qb->expr()->lte("{$p}_history.startDate", "{$p}_userHistory.startDate"),
                        $qb->expr()->orX(
                            $qb->expr()->isNull("{$p}_history.endDate"),
                            $qb->expr()->gt("{$p}_history.endDate", "{$p}_userHistory.startDate")
                        )
                    )
                )
            )
            ->andWhere($qb->expr()->in("{$p}_history.job", ":{$p}_jobs"))
            ->setParameter(
                "{$p}_jobs",
                $data['creator_job'],
            );
    }

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

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

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

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

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

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

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

        return new TranslatableMessage('export.filter.course.creator_job.Filtered by creator job: only %jobs%', [
            '%jobs%' => implode(', ', $creatorJobs),
        ]);
    }

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

    public function getTitle(): TranslatableMessage
    {
        return new TranslatableMessage('export.filter.course.creator_job.Filter by creator job');
    }
}
