<?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\Address;
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\Household\PersonHouseholdAddress;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class NotAssociatedWithAReferenceAddressFilter implements FilterInterface
{
    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.filter.course.not_having_address_reference.title';
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('date_calc', PickRollingDateType::class, [
            'label' => 'export.filter.course.not_having_address_reference.adress_at',
        ]);
    }

    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 [
            'exports.filter.course.not_having_address_reference.describe',
            [
                'date_calc' => $this->rollingDateConverter->convert($data['date_calc']),
            ],
        ];
    }

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $k = 'acp_not_associated_ref_filter';

        $qb
            ->leftJoin(
                'acp.locationHistories',
                $k,
                Join::WITH,
                "{$k}.period = acp AND {$k}.startDate <= :{$k}_date_calc AND ({$k}.endDate IS NULL OR {$k}.endDate > :{$k}_date_calc)"
            )
            ->leftJoin(
                PersonHouseholdAddress::class,
                "{$k}_p_address",
                Join::WITH,
                "{$k}.personLocation = {$k}_p_address.person AND {$k}_p_address.validFrom <= :{$k}_date_calc AND ({$k}_p_address.validTo IS NULL OR {$k}_p_address.validTo > :{$k}_date_calc)"
            )
            ->join(
                Address::class,
                "{$k}_address",
                Join::WITH,
                "{$k}_address.id = COALESCE(IDENTITY({$k}_p_address.address), IDENTITY({$k}.addressLocation))"
            )
        ;

        $qb->andWhere("{$k}_address.addressReference IS NULL");
        $qb->setParameter("{$k}_date_calc", $this->rollingDateConverter->convert($data['date_calc']));
    }

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