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

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;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class ChildrenNumberAggregator implements AggregatorInterface
{
    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter) {}

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        if (!\in_array('composition_children', $qb->getAllAliases(), true)) {
            $clause = $qb->expr()->andX(
                $qb->expr()->lte('composition_children.startDate', ':ondate_composition_children'),
                $qb->expr()->orX(
                    $qb->expr()->gt('composition_children.endDate', ':ondate_composition_children'),
                    $qb->expr()->isNull('composition_children.endDate')
                )
            );

            $qb->leftJoin('household.compositions', 'composition_children', Expr\Join::WITH, $clause);
        }

        $qb
            ->addSelect('composition_children.numberOfChildren AS childrennumber_aggregator')
            ->addGroupBy('childrennumber_aggregator');

        $qb->setParameter(
            'ondate_composition_children',
            $this->rollingDateConverter->convert($data['on_date'])
        );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('on_date', PickRollingDateType::class, []);
    }

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

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

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return static function (int|string|null $value): string {
            if ('_header' === $value) {
                return 'Number of children';
            }

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

            return (string) $value;
        };
    }

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

    public function getTitle(): string
    {
        return 'Group by number of children';
    }
}
