<?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\Export\ExportElementValidatedInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

final readonly class AgeAggregator implements AggregatorInterface, ExportElementValidatedInterface
{
    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        $qb->addSelect('DATE_DIFF(:date_age_calculation, person.birthdate)/365 as person_age');
        $qb->setParameter('date_age_calculation', $this->rollingDateConverter->convert($data['date_age_calculation']));
        $qb->addGroupBy('person_age');
    }

    public function applyOn(): string
    {
        return 'person';
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('date_age_calculation', PickRollingDateType::class, [
            'label' => 'Calculate age in relation to this date',
        ]);
    }

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

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

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return function ($value) {
            if ('_header' === $value) {
                return 'Age';
            }

            return $value ?? '';
        };
    }

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

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'Aggregate by age';
    }

    public function validateForm($data, ExecutionContextInterface $context): void
    {
        if (null === $data['date_age_calculation']) {
            $context->buildViolation('The date should not be empty')
                ->addViolation();
        }
    }
}
