<?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\Export\AggregatorInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class PostalCodeAggregator implements AggregatorInterface
{
    private const PREFIX = 'person_postal_code_agg';

    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('calc_date', PickRollingDateType::class, [
                'label' => 'export.aggregator.person.by_postal_code.at_date',
            ]);
    }

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

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

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

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

    public function getLabels($key, array $values, mixed $data): callable
    {
        return function (int|string|null $value): string {
            if ('_header' === $value) {
                return 'export.aggregator.person.by_postal_code.header';
            }

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

            return $value;
        };
    }

    public function getQueryKeys($data): array
    {
        return [self::PREFIX.'_postal_code_code', self::PREFIX.'_postal_code_label'];
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.aggregator.person.by_postal_code.title';
    }

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        $p = self::PREFIX;

        $qb
            ->leftJoin(
                'person.householdAddresses',
                "{$p}_household_addresses",
                Join::WITH,
                "{$p}_household_addresses.validFrom <= :{$p}_calc_date AND ({$p}_household_addresses.validTo IS NULL OR {$p}_household_addresses.validTo > :{$p}_calc_date)"
            )
            ->setParameter("{$p}_calc_date", $this->rollingDateConverter->convert($data['calc_date']))
            ->leftJoin("{$p}_household_addresses.address", "{$p}_address")
            ->leftJoin("{$p}_address.postcode", "{$p}_postal_code")
            ->addSelect("{$p}_postal_code.code AS {$p}_postal_code_code")
            ->addSelect("{$p}_postal_code.name AS {$p}_postal_code_label")
            ->addGroupBy("{$p}_postal_code_code")
            ->addGroupBy("{$p}_postal_code_label")
        ;
    }

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