<?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\Entity\Address;
use Chill\MainBundle\Export\ExportGenerationContext;
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\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;

class AddressRefStatusFilter implements \Chill\MainBundle\Export\FilterInterface
{
    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $subQuery =
            'SELECT 1
            FROM '.PersonHouseholdAddress::class.' person_filter_having_address_to_review_person_household_address
            JOIN person_filter_having_address_to_review_person_household_address.address person_filter_having_address_to_review_address
            WHERE
                person_filter_having_address_to_review_person_household_address.validFrom <= :person_filter_having_address_to_review_date
                AND
                    (person_filter_having_address_to_review_person_household_address.validTo IS NULL
                    OR person_filter_having_address_to_review_person_household_address.validTo > :person_filter_having_address_to_review_date)
                AND
                    person_filter_having_address_to_review_person_household_address.person = person
                AND person_filter_having_address_to_review_address.refStatus IN (:person_filter_having_address_to_review_ref_statuses)
            ';

        $qb
            ->andWhere(
                $qb->expr()->exists($subQuery)
            )
            ->setParameter(
                'person_filter_having_address_to_review_date',
                $this->rollingDateConverter->convert($data['date_calc'] ?? RollingDate::T_TODAY)
            )
            ->setParameter('person_filter_having_address_to_review_ref_statuses', $data['ref_statuses'] ?? [Address::ADDR_REFERENCE_STATUS_TO_REVIEW]);
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('date_calc', PickRollingDateType::class, [
                'label' => 'export.filter.person.by_address_ref_status.Address at date',
                'required' => true,
            ])
            ->add('ref_statuses', ChoiceType::class, [
                'label' => 'export.filter.person.by_address_ref_status.Status',
                'choices' => [Address::ADDR_REFERENCE_STATUS_TO_REVIEW, Address::ADDR_REFERENCE_STATUS_REVIEWED, Address::ADDR_REFERENCE_STATUS_MATCH],
                'choice_label' => fn (string $item) => 'export.filter.person.by_address_ref_status.'.$item,
                'multiple' => true,
                'expanded' => true,
            ]);
    }

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

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

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

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

    public function describeAction($data, ExportGenerationContext $context): string|\Symfony\Contracts\Translation\TranslatableInterface|array
    {
        return [
            'export.filter.person.by_address_ref_status.Filtered by person\'s address status computed at %datecalc%, only %statuses%',
            [
                '%datecalc%' => $this->rollingDateConverter->convert($data['date_calc'])->format('Y-m-d'),
                '%statuses%' => implode(
                    ', ',
                    array_map(
                        fn (string $item) => 'export.filter.person.by_address_ref_status.'.$item,
                        $data['ref_statuses'] ?? RollingDate::T_TODAY
                    )
                ),
            ],
        ];
    }

    public function getTitle(): string
    {
        return 'export.filter.person.by_address_ref_status.Filter by person\'s address ref status';
    }
}
