<?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\Entity\GeographicalUnit\SimpleGeographicalUnitDTO;
use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
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\AccompanyingPeriod;
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;

/**
 * Filter accompanying period by geographical zone.
 */
class GeographicalUnitStatFilter implements FilterInterface
{
    public function __construct(
        private readonly GeographicalUnitRepositoryInterface $geographicalUnitRepository,
        private readonly GeographicalUnitLayerRepositoryInterface $geographicalUnitLayerRepository,
        private readonly TranslatableStringHelperInterface $translatableStringHelper,
        private readonly RollingDateConverterInterface $rollingDateConverter,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $subQueryDql =
            'SELECT
                1
            FROM '.AccompanyingPeriod\AccompanyingPeriodLocationHistory::class.' acp_geog_filter_location_history
            JOIN acp_geog_filter_location_history.period acp_geog_filter_location_history_period
            LEFT JOIN '.PersonHouseholdAddress::class.' acp_geog_filter_address_person_location
                WITH IDENTITY(acp_geog_filter_location_history.personLocation) = IDENTITY(acp_geog_filter_address_person_location.person)
                AND
                (acp_geog_filter_address_person_location.validFrom < LEAST(:acp_geog_filter_date, acp_geog_filter_location_history_period.closingDate) AND (
                    acp_geog_filter_address_person_location.validTo IS NULL OR acp_geog_filter_address_person_location.validTo > LEAST(:acp_geog_filter_date, acp_geog_filter_location_history_period.closingDate)
                ))
            LEFT JOIN '.Address::class.' acp_geog_filter_address
                WITH COALESCE(IDENTITY(acp_geog_filter_address_person_location.address), IDENTITY(acp_geog_filter_location_history.addressLocation)) = acp_geog_filter_address.id
            LEFT JOIN acp_geog_filter_address.geographicalUnits acp_geog_filter_units
            WHERE
                (acp_geog_filter_location_history.startDate <= LEAST(:acp_geog_filter_date, acp_geog_filter_location_history_period.closingDate) AND (
                    acp_geog_filter_location_history.endDate IS NULL OR acp_geog_filter_location_history.endDate > LEAST(:acp_geog_filter_date, acp_geog_filter_location_history_period.closingDate)
                ))
                AND acp_geog_filter_units IN (:acp_geog_filter_units)
                AND acp_geog_filter_location_history.period = acp.id
            ';

        $qb
            ->andWhere($qb->expr()->exists($subQueryDql))
            ->setParameter(
                'acp_geog_filter_date',
                $this->rollingDateConverter->convert($data['date_calc'])
            )
            ->setParameter('acp_geog_filter_units', array_map(
                static fn (SimpleGeographicalUnitDTO $unitDTO) => $unitDTO->id,
                $data['units'] instanceof Collection ? $data['units']->toArray() : $data['units']
            ));
    }

    public function applyOn(): string
    {
        return Declarations::ACP_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): array
    {
        return ['Filtered by geographic unit: computed at %date%, only in %units%', [
            '%date%' => $this->rollingDateConverter->convert($data['date_calc'])->format('d-m-Y'),
            '%units' => implode(
                ', ',
                array_map(
                    fn (SimpleGeographicalUnitDTO $item) => $this->translatableStringHelper->localize($this->geographicalUnitLayerRepository->find($item->layerId)->getName()).' > '.$item->unitName,
                    $data['units']
                )
            ),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter by geographical unit';
    }
}
