<?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\Aggregator\AccompanyingCourseAggregators;

use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\GeographicalUnitLayer;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\GeographicalUnitLayerRepositoryInterface;
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\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class GeographicalUnitStatAggregator implements AggregatorInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

    public function __construct(
        private GeographicalUnitLayerRepositoryInterface $geographicalUnitLayerRepository,
        private TranslatableStringHelperInterface $translatableStringHelper,
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        $qb->leftJoin('acp.locationHistories', 'acp_geog_agg_location_history');

        $qb->andWhere(
            $qb->expr()->andX(
                'acp_geog_agg_location_history.startDate <= LEAST(:acp_geog_aggregator_date, acp.closingDate)',
                $qb->expr()->orX(
                    'acp_geog_agg_location_history.endDate IS NULL',
                    'acp_geog_agg_location_history.endDate > LEAST(:acp_geog_aggregator_date, acp.closingDate)'
                )
            )
        );

        // link between location history and person
        $qb->leftJoin(
            PersonHouseholdAddress::class,
            'acp_geog_agg_address_person_location',
            Join::WITH,
            $qb->expr()->andX(
                'IDENTITY(acp_geog_agg_address_person_location.person) = IDENTITY(acp_geog_agg_location_history.personLocation)',
                'acp_geog_agg_address_person_location.validFrom <= LEAST(:acp_geog_aggregator_date, acp.closingDate)',
                $qb->expr()->orX(
                    'acp_geog_agg_address_person_location.validTo > LEAST(:acp_geog_aggregator_date, acp.closingDate)',
                    $qb->expr()->isNull('acp_geog_agg_address_person_location.validTo')
                )
            )
        );

        $qb->setParameter(
            'acp_geog_aggregator_date',
            $this->rollingDateConverter->convert($data['date_calc'])
        );

        // we finally find an address
        $qb->leftJoin(
            Address::class,
            'acp_geog_agg_address',
            Join::WITH,
            'COALESCE(IDENTITY(acp_geog_agg_address_person_location.address), IDENTITY(acp_geog_agg_location_history.addressLocation)) = acp_geog_agg_address.id'
        );

        // and we do a join with units
        $qb->leftJoin(
            'acp_geog_agg_address.geographicalUnits',
            'acp_geog_units'
        );

        $qb->andWhere(
            $qb->expr()->orX(
                $qb->expr()->isNull('acp_geog_units'),
                $qb->expr()->in('acp_geog_units.layer', ':acp_geog_unit_layer')
            )
        );

        $qb->setParameter('acp_geog_unit_layer', $data['level']);

        // we add group by
        $qb
            ->addSelect('acp_geog_units.unitName AS acp_geog_agg_unitname')
            ->addSelect('acp_geog_units.unitRefId AS acp_geog_agg_unitrefid')
            ->addGroupBy('acp_geog_agg_unitname')
            ->addGroupBy('acp_geog_agg_unitrefid');
    }

    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('level', EntityType::class, [
                'label' => 'Geographical layer',
                'placeholder' => 'Select a geographical layer',
                'class' => GeographicalUnitLayer::class,
                'choices' => $this->geographicalUnitLayerRepository->findAllHavingUnits(),
                'choice_label' => fn (GeographicalUnitLayer $item) => $this->translatableStringHelper->localize($item->getName()),
                'multiple' => true,
                'expanded' => true,
            ]);
    }

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

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

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return match ($key) {
            'acp_geog_agg_unitname' => static function ($value): string {
                if ('_header' === $value) {
                    return 'acp_geog_agg_unitname';
                }

                if (null === $value || '' === $value) {
                    return '';
                }

                return $value;
            },
            'acp_geog_agg_unitrefid' => static function ($value): string {
                if ('_header' === $value) {
                    return 'acp_geog_agg_unitrefid';
                }

                if (null === $value) {
                    return '';
                }

                return $value;
            },
            default => throw new \UnexpectedValueException('this value should not happens'),
        };
    }

    public function getQueryKeys($data): array
    {
        return ['acp_geog_agg_unitname', 'acp_geog_agg_unitrefid'];
    }

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