<?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\DataTransformerInterface;
use Chill\MainBundle\Export\ExportDataNormalizerTrait;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\UserJobRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\AccompanyingPeriod\UserHistory;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class UserJobFilter implements FilterInterface, DataTransformerInterface
{
    use ExportDataNormalizerTrait;

    private const PREFIX = 'acp_filter_user_job';

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

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

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

        $qb->andWhere(
            $qb->expr()->exists(
                sprintf(
                    <<<DQL
                    SELECT 1
                    FROM %s {$p}_userHistory
                    JOIN %s {$p}_userJobHistory
                        WITH
                            {$p}_userHistory.user = {$p}_userJobHistory.user
                            AND OVERLAPSI({$p}_userHistory.startDate, {$p}_userHistory.endDate),({$p}_userJobHistory.startDate, {$p}_userJobHistory.endDate) = TRUE
                    WHERE {$p}_userHistory.accompanyingPeriod = acp
                        AND {$p}_userHistory.startDate <= :{$p}_endDate
                        AND ({$p}_userHistory.endDate IS NULL OR {$p}_userHistory.endDate > :{$p}_startDate)
                        AND {$p}_userJobHistory.startDate <= :{$p}_endDate
                        AND ({$p}_userJobHistory.endDate IS NULL OR {$p}_userJobHistory.endDate > :{$p}_startDate)
                        AND {$p}_userJobHistory.job IN (:{$p}_jobs)
                    DQL,
                    UserHistory::class,
                    UserJobHistory::class,
                ),
            )
        )
            ->setParameter("{$p}_jobs", $data['jobs'])
            ->setParameter("{$p}_startDate", $this->rollingDateConverter->convert($data['start_date']))
            ->setParameter("{$p}_endDate", $this->rollingDateConverter->convert($data['end_date']))
        ;
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('jobs', EntityType::class, [
                'class' => UserJob::class,
                'choices' => $this->userJobRepository->findAllActive(),
                'multiple' => true,
                'expanded' => true,
                'choice_label' => fn (UserJob $job) => $this->translatableStringHelper->localize($job->getLabel()),
                'label' => 'Job',
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_user_job.Start from',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_user_job.Until',
            ])
        ;
    }

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return [
            'exports.filter.course.by_user_job.Filtered by user job: only job', [
                'job' => implode(
                    ', ',
                    array_map(
                        fn (UserJob $job) => $this->translatableStringHelper->localize($job->getLabel()),
                        $data['jobs'] instanceof Collection ? $data['jobs']->toArray() : $data['jobs']
                    )
                ),
                'startDate' => $this->rollingDateConverter->convert($data['start_date']),
                'endDate' => $this->rollingDateConverter->convert($data['end_date']),
            ],
        ];
    }

    public function getFormDefaultData(): array
    {
        return [
            'jobs' => [],
            'start_date' => new RollingDate(RollingDate::T_YEAR_CURRENT_START),
            'end_date' => new RollingDate(RollingDate::T_TODAY),
        ];
    }

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

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        $default = $this->getFormDefaultData();

        return [
            'jobs' => $this->denormalizeDoctrineEntity($formData['jobs'], $this->userJobRepository),
            'start_date' => array_key_exists('start_date', $formData) ? RollingDate::fromNormalized($formData['start_date']) : $default['start_date'],
            'end_date' => array_key_exists('end_date', $formData) ? RollingDate::fromNormalized($formData['end_date']) : $default['end_date'],
        ];
    }

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

    public function transformData(?array $before): array
    {
        $default = $this->getFormDefaultData();

        if (null === $before) {
            return $default;
        }

        if (!array_key_exists('start_date', $before) || null === $before['start_date']) {
            $before['start_date'] = $default['start_date'];
        }

        if (!array_key_exists('end_date', $before) || null === $before['end_date']) {
            $before['end_date'] = $default['end_date'];
        }

        return $before;
    }

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