<?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\Center;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\CenterRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\UserHistory;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;

/**
 * Filter accompanying periods by the main center of their referrer (at a given date).
 */
final readonly class ReferrerMainCenterFilter implements FilterInterface
{
    private const UH = 'acp_referrer_main_center_filter_uh';
    private const DATE_PARAM_SINCE = 'acp_referrer_main_center_filter_date_since';
    private const DATE_PARAM_UNTIL = 'acp_referrer_main_center_filter_date_until';

    private const CENTER_PARAM = 'acp_referrer_main_center_filter_center';

    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
        private CenterRepositoryInterface $centerRepository,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $dql = 'SELECT 1 FROM '.UserHistory::class.' '.self::UH.'
        JOIN '.self::UH.'.user '.self::UH.'_user
        WHERE acp = '.self::UH.'.accompanyingPeriod
        AND (
            '.self::UH.'.startDate < :'.self::DATE_PARAM_UNTIL.'
            AND (
                '.self::UH.'.endDate IS NULL OR '.self::UH.'.endDate >= :'.self::DATE_PARAM_SINCE.'
            )
        )
        AND '.self::UH.'_user.mainCenter IN (:'.self::CENTER_PARAM.')';

        $qb->andWhere(
            $qb->expr()->exists($dql)
        );
        $qb
            ->setParameter(self::DATE_PARAM_SINCE, $this->rollingDateConverter->convert($data['date_calc_since']))
            ->setParameter(self::DATE_PARAM_UNTIL, $this->rollingDateConverter->convert($data['date_calc_until']))
            ->setParameter(self::CENTER_PARAM, $data['centers']);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('centers', EntityType::class, [
                'class' => Center::class,
                'choices' => $this->centerRepository->findActive(),
                'multiple' => true,
                'expanded' => false,
                'choice_label' => static fn (Center $c) => $c->getName(),
                'required' => true,
                'label' => 'common.centers',
                'attr' => [
                    'class' => 'select2',
                ],
            ])
            ->add('date_calc_since', PickRollingDateType::class, [
                'label' => 'person.export.period.filter.by_referrer_main_center.referrer_since',
                'required' => true,
            ])
            ->add('date_calc_until', PickRollingDateType::class, [
                'label' => 'person.export.period.filter.by_referrer_main_center.referrer_until',
                'required' => true,
            ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return [
            'centers' => array_values(array_map(static fn (Center $c) => $c->getId(), $formData['centers'])),
            'date_calc_since' => $formData['date_calc_since']->normalize(),
            'date_calc_until' => $formData['date_calc_until']->normalize(),
        ];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return [
            'centers' => array_values(array_filter(array_map(
                fn (int $id) => $this->centerRepository->find($id),
                $formData['centers'] ?? []
            ))),
            'date_calc_since' => RollingDate::fromNormalized($formData['date_calc_since']),
            'date_calc_until' => RollingDate::fromNormalized($formData['date_calc_until']),
        ];
    }

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

    public function describeAction($data, ExportGenerationContext $context): TranslatableInterface
    {
        $names = array_map(static fn (Center $c) => $c->getName(), $data['centers']);

        return new TranslatableMessage(
            'person.export.period.filter.by_referrer_main_center.description',
            [
                'centers' => implode(', ', $names),
                'date_since' => $this->rollingDateConverter->convert($data['date_calc_since']),
                'date_until' => $this->rollingDateConverter->convert($data['date_calc_until']),
            ]
        );
    }

    public function getTitle(): TranslatableInterface
    {
        return new TranslatableMessage('person.export.period.filter.by_referrer_main_center.title');
    }
}
