<?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\Scope;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Repository\ScopeRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Templating\TranslatableStringHelper;
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 ScopeFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'acp_work_action_filter_user_scope';

    public function __construct(
        private TranslatableStringHelper $translatableStringHelper,
        private ScopeRepositoryInterface $scopeRepository,
    ) {}

    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.scopeHistories {$p}_scope_history
                WHERE {$p}_ref_history.accompanyingPeriodWork = acpw AND {$p}_scope_history.scope IN (:{$p}_scope) AND {$p}_scope_history.startDate <= {$p}_ref_history.startDate
                AND ({$p}_scope_history.endDate IS NULL or {$p}_scope_history.endDate >= {$p}_ref_history.startDate))"
        )
            ->setParameter("{$p}_scope", $data['scope']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('scope', EntityType::class, [
                'class' => Scope::class,
                'choices' => $this->scopeRepository->findAllActive(),
                'choice_label' => fn (Scope $s) => $this->translatableStringHelper->localize(
                    $s->getName()
                ),
                'multiple' => true,
                'expanded' => true,
            ])
        ;
    }

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

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

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

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

        foreach ($data['scope'] as $s) {
            $scopes[] = $this->translatableStringHelper->localize(
                $s->getName()
            );
        }

        return ['export.filter.work.by_user_scope.Filtered by treating agent scope: only %scopes%', [
            '%scopes%' => implode(', ', $scopes),
        ]];
    }

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

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