<?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\PersonFilters;

use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\Person\ResidentialAddress;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\QueryBuilder;

class ResidentialAddressAtUserFilter implements FilterInterface
{
    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        if (!\in_array('resaddr', $qb->getAllAliases(), true)) {
            $qb->join(ResidentialAddress::class, 'resaddr', Expr\Join::WITH, 'resaddr.person = person');
        }

        if (!\in_array('center', $qb->getAllAliases(), true)) {
            $qb->join('person.center', 'center');
        }

        $where = $qb->getDQLPart('where');

        $clause = $qb->expr()->andX(
            $qb->expr()->isNotNull('resaddr.hostPerson'),
            $qb->expr()->orX(
                $qb->expr()->between(':date', 'resaddr.startDate', 'resaddr.endDate'),
                $qb->expr()->andX(
                    $qb->expr()->lte('resaddr.startDate', ':date'),
                    $qb->expr()->isNull('resaddr.endDate')
                )
            )
        );

        if ($where instanceof Andx) {
            $where->add($clause);
        } else {
            $where = $qb->expr()->andX($clause);
        }

        $qb->setParameter(
            'date',
            $this->rollingDateConverter->convert($data['date_calc'])
        );
        $qb->add('where', $where);
    }

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

    public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder): void
    {
        $builder->add('date_calc', PickRollingDateType::class, [
            'label' => 'Date during which residential address was valid',
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['date_calc' => $formData['date_calc']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['date_calc' => RollingDate::fromNormalized($formData['date_calc'])];
    }

    public function getFormDefaultData(): array
    {
        return ['date_calc' => new RollingDate(RollingDate::T_TODAY)];
    }

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return ["Filtered by person's who have a residential address located at another user"];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return "Filter by person's who have a residential address located at another user";
    }
}
