<?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\PersonAggregators;

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\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 GeographicalUnitAggregator 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(
                'person.householdAddresses',
                'person_geog_agg_current_household_address',
                Join::WITH,
                $qb->expr()->andX(
                    $qb->expr()->lte('person_geog_agg_current_household_address.validFrom', ':person_geog_agg_date'),
                    $qb->expr()->orX(
                        $qb->expr()->isNull('person_geog_agg_current_household_address.validTo'),
                        $qb->expr()->gt('person_geog_agg_current_household_address.validTo', ':person_geog_agg_date')
                    )
                )
            )
            ->leftJoin(
                'person_geog_agg_current_household_address.address',
                'person_geog_agg_address'
            )
            ->leftJoin(
                'person_geog_agg_address.geographicalUnits',
                'person_geog_agg_geog_unit'
            )
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->isNull('person_geog_agg_geog_unit'),
                    $qb->expr()->in('person_geog_agg_geog_unit.layer', ':person_geog_agg_layers')
                )
            )
            ->setParameter(
                'person_geog_agg_date',
                $this->rollingDateConverter->convert($data['date_calc'])
            )
            ->setParameter('person_geog_agg_layers', $data['level'])
            ->addSelect('person_geog_agg_geog_unit.unitName AS geog_unit_name')
            ->addSelect('person_geog_agg_geog_unit.unitRefId AS geog_unit_key')
            ->addGroupBy('geog_unit_name')
            ->addGroupBy('geog_unit_key');
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('date_calc', PickRollingDateType::class, [
                'label' => 'Address valid at this 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 static function getDefaultAlias(): string
    {
        return 'person_geog_agg';
    }

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

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

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

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

                return $value;
            },
            default => throw new \LogicException('key not supported'),
        };
    }

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

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Group people by geographical unit based on his address';
    }
}
