<?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\Scope;
use Chill\MainBundle\Entity\User\UserScopeHistory;
use Chill\MainBundle\Export\DataTransformerInterface;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\ScopeRepositoryInterface;
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 UserScopeFilter implements FilterInterface, DataTransformerInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'acp_filter_main_scope';

    public function __construct(
        private ScopeRepositoryInterface $scopeRepository,
        private TranslatableStringHelper $translatableStringHelper,
        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}_userScopeHistory
                        WITH
                            {$p}_userHistory.user = {$p}_userScopeHistory.user
                            AND OVERLAPSI({$p}_userHistory.startDate, {$p}_userHistory.endDate),({$p}_userScopeHistory.startDate, {$p}_userScopeHistory.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}_userScopeHistory.startDate <= :{$p}_endDate
                        AND ({$p}_userScopeHistory.endDate IS NULL OR {$p}_userScopeHistory.endDate > :{$p}_startDate)
                        AND {$p}_userScopeHistory.scope IN (:{$p}_scopes)
                    DQL,
                    UserHistory::class,
                    UserScopeHistory::class,
                ),
            )
        )
            ->setParameter("{$p}_scopes", $data['scopes'])
            ->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('scopes', EntityType::class, [
                'class' => Scope::class,
                'choices' => $this->scopeRepository->findAllActive(),
                'choice_label' => fn (Scope $s) => $this->translatableStringHelper->localize($s->getName()),
                'multiple' => true,
                'expanded' => true,
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_user_scope.Start from',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_user_scope.Until',
            ]);
    }

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

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

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

        return [
            'scopes' => $this->denormalizeDoctrineEntity($formData['scopes'], $this->scopeRepository),
            '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 describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return [
            'exports.filter.course.by_user_scope.Filtered by user main scope: only scopes', [
                'scopes' => implode(
                    ', ',
                    array_map(
                        fn (Scope $s) => $this->translatableStringHelper->localize($s->getName()),
                        $data['scopes'] instanceof Collection ? $data['scopes']->toArray() : $data['scopes']
                    )
                ),
                'startDate' => $this->rollingDateConverter->convert($data['start_date']),
                'endDate' => $this->rollingDateConverter->convert($data['end_date']),
            ],
        ];
    }

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

    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_scope.Filter by user scope';
    }
}
