<?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\Scope;
use Chill\MainBundle\Entity\User\UserScopeHistory;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Repository\ScopeRepositoryInterface;
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;
use Symfony\Contracts\Translation\TranslatorInterface;

class ScopeFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'cal_filter_scope';

    public function __construct(
        protected TranslatorInterface $translator,
        private readonly TranslatableStringHelper $translatableStringHelper,
        private readonly ScopeRepositoryInterface $scopeRepository,
    ) {}

    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(
                UserScopeHistory::class,
                "{$p}_history",
                Join::WITH,
                $qb->expr()->eq("{$p}_history.user", "{$p}_user")
            )
            // scope_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.scope", ":{$p}_scope"))
            ->setParameter(
                "{$p}_scope",
                $data['scope']
            );
    }

    public function applyOn(): string
    {
        return Declarations::CALENDAR_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.calendar.agent_scope.Filtered by agent scope: only %scopes%', [
            '%scopes%' => implode(', ', $scopes),
        ]];
    }

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

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