<?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\SocialWorkFilters;

use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Repository\UserJobRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkReferrerHistory;
use Chill\PersonBundle\Export\Declarations;
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 = 'acp_work_action_filter_user_job';

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

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

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

        $qb->andWhere(
            'EXISTS (SELECT 1 FROM '.AccompanyingPeriodWorkReferrerHistory::class." {$p}_ref_history
                JOIN {$p}_ref_history.user {$p}_ref_history_user JOIN {$p}_ref_history_user.jobHistories {$p}_job_history
                WHERE {$p}_ref_history.accompanyingPeriodWork = acpw AND {$p}_job_history.job IN (:{$p}_job) AND {$p}_job_history.startDate <= {$p}_ref_history.startDate
                AND ({$p}_job_history.endDate IS NULL or {$p}_job_history.endDate >= {$p}_ref_history.startDate))"
        );

        $qb->setParameter("{$p}_job", $data['job']);
    }

    public function applyOn(): string
    {
        return Declarations::SOCIAL_WORK_ACTION_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): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        $userjobs = [];

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

        return ['export.filter.work.by_user_job.Filtered by treating agent job: only %jobs%', [
            '%jobs%' => implode(', ', $userjobs),
        ]];
    }

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

    public function getTitle(): string
    {
        return 'export.filter.work.by_user_job.Filter by treating agent job';
    }
}
