<?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\ActivityBundle\Export\Filter;

use Chill\ActivityBundle\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;

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

    public function __construct(
        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('activity.createdBy', "{$p}_user")
            ->leftJoin(
                UserScopeHistory::class,
                "{$p}_history",
                Join::WITH,
                $qb->expr()->eq("{$p}_history.user", "{$p}_user")
            )
            // scope_at based on activity.date
            ->andWhere(
                $qb->expr()->andX(
                    $qb->expr()->lte("{$p}_history.startDate", 'activity.date'),
                    $qb->expr()->orX(
                        $qb->expr()->isNull("{$p}_history.endDate"),
                        $qb->expr()->gt("{$p}_history.endDate", 'activity.date')
                    )
                )
            )
            ->andWhere(
                $qb->expr()->in("{$p}_history.scope", ":{$p}_scopes")
            )
            ->setParameter(
                "{$p}_scopes",
                $data['scopes'],
            );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('scopes', 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 ['scopes' => $this->normalizeDoctrineEntity($formData['scopes'])];
    }

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

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

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

        return ['export.filter.activity.by_creator_scope.Filtered activity by user scope: only %scopes%', [
            '%scopes%' => implode(', ', $scopes),
        ]];
    }

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

    public function getTitle(): string
    {
        return 'export.filter.activity.by_creator_scope.Filter activity by user scope';
    }
}
