<?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\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Form\Type\PickUserOrMeDynamicType;
use Chill\MainBundle\Repository\UserRepository;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use src\Bundle\ChillPersonBundle\Tests\Export\Filter\AccompanyingCourseFilters\ReferrerFilterBetweenDatesTest;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Class ReferrerFilterBetweenDates.
 *
 * This class implements the FilterInterface and provides functionality to filter query results
 * based on a range of dates and accepted referrers.
 *
 * @see ReferrerFilterBetweenDatesTest for tests
 */
final readonly class ReferrerFilterBetweenDates implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;
    private const A = 'acp_referrer_filter_uhistory';

    private const P = 'acp_referrer_filter_date_start';
    private const Q = 'acp_referrer_filter_date_end';

    private const PU = 'acp_referrer_filter_users';

    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
        private UserRender $userRender,
        private UserRepository $userRepository,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $history = self::A;
        $start = self::P;
        $end = self::Q;
        $users = self::PU;

        $qb
            ->join('acp.userHistories', self::A)
            ->andWhere(
                "OVERLAPSI({$history}.startDate, {$history}.endDate),(:{$start}, :{$end}) = TRUE"
            )
            ->andWhere(
                "{$history}.user IN (:{$users})",
            )
            ->setParameter($users, $this->userOrMe($data['accepted_referrers'], $exportGenerationContext))
            ->setParameter($start, $this->rollingDateConverter->convert($data['start_date']))
            ->setParameter($end, $this->rollingDateConverter->convert($data['end_date']));
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_referrers', PickUserOrMeDynamicType::class, [
                'multiple' => true,
            ])
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_referrer_between_dates.start date',
                'required' => true,
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.course.by_referrer_between_dates.end date',
                'required' => true,
            ]);
    }

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

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

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_referrers' => $this->denormalizeUserOrMe($formData['accepted_referrers'], $this->userRepository),
            'start_date' => RollingDate::fromNormalized($formData['start_date']), 'end_date' => RollingDate::fromNormalized($formData['end_date'])];
    }

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

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

        foreach ($this->userOrMe($data['accepted_referrers'], $context) as $r) {
            $users[] = $this->userRender->renderString($r, []);
        }

        return [
            'exports.filter.course.by_referrer_between_dates.description', [
                'agents' => implode(', ', $users),
                'start_date' => $this->rollingDateConverter->convert($data['start_date']),
                'end_date' => $this->rollingDateConverter->convert($data['end_date']),
            ], ];
    }

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