<?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\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\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodInfo;
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;

/**
 * Filter course where a user with the given scope is "working" on it.
 *
 * Makes use of AccompanyingPeriodInfo
 */
readonly class ScopeWorkingOnCourseFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const PREFIX = 'acp_filter_user_scope_working_on_course';

    public function __construct(
        private ScopeRepositoryInterface $scopeRepository,
        private RollingDateConverterInterface $rollingDateConverter,
        private TranslatableStringHelperInterface $translatableStringHelper,
    ) {}

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

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

        $qb
            ->andWhere(
                $qb->expr()->exists(
                    'SELECT 1 FROM '.AccompanyingPeriodInfo::class." {$p}_info  "
                    ."JOIN {$p}_info.user {$p}_user "
                    .'JOIN '.UserScopeHistory::class." {$p}_history WITH {$p}_history.user = {$p}_user "
                    ."WHERE IDENTITY({$p}_info.accompanyingPeriod) = acp.id "
                    ."AND {$p}_history.scope IN ( :{$p}_scopes ) "
                    // scope_at based on _info.infoDate
                    ."AND {$p}_history.startDate <= {$p}_info.infoDate "
                    ."AND ({$p}_history.endDate IS NULL OR {$p}_history.endDate > {$p}_info.infoDate) "
                    ."AND {$p}_info.infoDate >= :{$p}_start AND {$p}_info.infoDate < :{$p}_end"
                )
            )
            ->setParameter("{$p}_scopes", $data['scopes'])
            ->setParameter(
                "{$p}_start",
                $this->rollingDateConverter->convert($data['start_date']),
            )
            ->setParameter(
                "{$p}_end",
                $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 $scope) => $this->translatableStringHelper->localize($scope->getName()),
                'multiple' => true,
                'expanded' => true,
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_scope_working.Scope working after',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_scope_working.Scope working before',
            ])
        ;
    }

    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
    {
        return ['scopes' => $this->denormalizeDoctrineEntity($formData['scopes'], $this->scopeRepository), 'start_date' => RollingDate::fromNormalized($formData['start_date']), 'end_date' => RollingDate::fromNormalized($formData['end_date'])];
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'export.filter.course.by_scope_working.Filtered by scope working on course: only %scopes%, between %start_date% and %end_date%', [
                '%scopes%' => implode(
                    ', ',
                    array_map(
                        fn (Scope $scope) => $this->translatableStringHelper->localize($scope->getName()),
                        $data['scopes'] instanceof Collection ? $data['scopes']->toArray() : $data['scopes']
                    )
                ),
                '%start_date%' => $this->rollingDateConverter->convert($data['start_date'])?->format('d-m-Y'),
                '%end_date%' => $this->rollingDateConverter->convert($data['end_date'])?->format('d-m-Y'),
            ],
        ];
    }

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

    public function getTitle(): string
    {
        return 'export.filter.course.by_scope_working.title';
    }
}
