<?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\GeographicalUnit\SimpleGeographicalUnitDTO;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\GeographicalUnitLayerRepositoryInterface;
use Chill\MainBundle\Repository\GeographicalUnitRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Household\PersonHouseholdAddress;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class GeographicalUnitFilter implements \Chill\MainBundle\Export\FilterInterface
{
    public function __construct(
        private GeographicalUnitRepositoryInterface $geographicalUnitRepository,
        private GeographicalUnitLayerRepositoryInterface $geographicalUnitLayerRepository,
        private TranslatableStringHelperInterface $translatableStringHelper,
        private 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_geog_person_household_address
            JOIN person_filter_geog_person_household_address.address person_filter_geog_address
            JOIN person_filter_geog_address.geographicalUnits person_filter_geog_unit
            WHERE
                person_filter_geog_person_household_address.validFrom <= :person_filter_geog_date
                AND
                    (person_filter_geog_person_household_address.validTo IS NULL
                    OR person_filter_geog_person_household_address.validTo > :person_filter_geog_date)
                AND
                    person_filter_geog_unit IN (:person_filter_geog_units)
                AND
                    person_filter_geog_person_household_address.person = person
            ';

        $qb
            ->andWhere(
                $qb->expr()->exists($subQuery)
            )
            ->setParameter(
                'person_filter_geog_date',
                $this->rollingDateConverter->convert($data['date_calc'])
            )
            ->setParameter('person_filter_geog_units', array_map(static fn (SimpleGeographicalUnitDTO $unitDTO) => $unitDTO->id, $data['units']));
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('date_calc', PickRollingDateType::class, [
                'label' => 'Compute geographical location at date',
                'required' => true,
            ])
            ->add('units', ChoiceType::class, [
                'label' => 'Geographical unit',
                'placeholder' => 'Select a geographical unit',
                'choices' => $this->geographicalUnitRepository->findAll(),
                'choice_value' => static fn (SimpleGeographicalUnitDTO $item) => $item->id,
                'choice_label' => fn (SimpleGeographicalUnitDTO $item) => $this->translatableStringHelper->localize($this->geographicalUnitLayerRepository->find($item->layerId)->getName()).' > '.$item->unitName,
                'attr' => [
                    'class' => 'select2',
                ],
                'multiple' => true,
            ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return [
            'date_calc' => $formData['date_calc']->normalize(),
            'units' => array_map(static fn (SimpleGeographicalUnitDTO $unitDTO) => $unitDTO->id, $formData['units']),
        ];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        $units = array_filter(
            array_map(
                fn (int $id) => $this->geographicalUnitRepository->findSimpleGeographicalUnit($id),
                $formData['units'],
            ),
            static fn (?SimpleGeographicalUnitDTO $unitDTO) => null !== $unitDTO,
        );

        return ['date_calc' => RollingDate::fromNormalized($formData['date_calc']), 'units' => $units];
    }

    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 [
            'export.filter.by_geog_unit.Filtered by person\'s geographical unit (based on address) computed at %datecalc%, only %units%',
            [
                '%datecalc%' => $this->rollingDateConverter->convert($data['date_calc'])->format('Y-m-d'),
                '%units%' => implode(
                    ', ',
                    array_map(
                        fn (SimpleGeographicalUnitDTO $item) => $this->translatableStringHelper->localize($this->geographicalUnitLayerRepository->find($item->layerId)->getName()).' > '.$item->unitName,
                        $data['units'] instanceof Collection ? $data['units']->toArray() : $data['units']
                    )
                ),
            ],
        ];
    }

    public function getTitle(): string
    {
        return 'Filter by person\'s geographical unit (based on address)';
    }
}
