<?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\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\Person\ResidentialAddress;
use Chill\PersonBundle\Export\Declarations;
use Chill\ThirdPartyBundle\Entity\ThirdPartyCategory;
use Chill\ThirdPartyBundle\Repository\ThirdPartyCategoryRepository;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class ResidentialAddressAtThirdpartyFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
        private TranslatableStringHelper $translatableStringHelper,
        private ThirdPartyCategoryRepository $thirdPartyCategoryRepository,
    ) {}

    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');
        }

        if (!\in_array('tparty', $qb->getAllAliases(), true)) {
            $qb->join('resaddr.hostThirdParty', 'tparty');
        }

        if (!\in_array('tpartycat', $qb->getAllAliases(), true)) {
            $qb->join('tparty.categories', 'tpartycat');
        }

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

        $clause = $qb->expr()->andX(
            $qb->expr()->isNotNull('resaddr.hostThirdParty'),
            $qb->expr()->in('tpartycat.id', ':type'),
            $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 Expr\Andx) {
            $where->add($clause);
        } else {
            $where = $qb->expr()->andX($clause);
        }

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

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('thirdparty_cat', EntityType::class, [
            'class' => ThirdPartyCategory::class,
            'label' => 'Category',
            'choice_label' => fn (ThirdPartyCategory $tpc) => $this->translatableStringHelper->localize($tpc->getName()),
            'multiple' => true,
            'expanded' => true,
        ]);

        $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 ['thirdparty_cat' => $this->normalizeDoctrineEntity($formData['thirdparty_cat']), 'date_calc' => $formData['date_calc']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['thirdparty_cat' => $this->denormalizeDoctrineEntity($formData['thirdparty_cat'], $this->thirdPartyCategoryRepository), '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 a thirdparty of type %thirdparty_type% and valid on %date_calc%', [
            '%thirdparty_type%' => $this->translatableStringHelper->localize($data['thirdparty_cat'][0]->getName()),
            '%date_calc%' => $this->rollingDateConverter->convert($data['date_calc'])->format('d-m-Y'),
        ]];
    }

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