<?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\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Repository\Household\HouseholdCompositionTypeRepository;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class CompositionAggregator implements AggregatorInterface
{
    public function __construct(private readonly HouseholdCompositionTypeRepository $typeRepository, private readonly TranslatableStringHelper $translatableStringHelper, 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_type', $qb->getAllAliases(), true)) {
            $clause = $qb->expr()->andX(
                $qb->expr()->lte('composition_type.startDate', ':ondate_composition_type'),
                $qb->expr()->orX(
                    $qb->expr()->gt('composition_type.endDate', ':ondate_composition_type'),
                    $qb->expr()->isNull('composition_type.endDate')
                )
            );

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

        $qb
            ->addSelect('IDENTITY(composition_type.householdCompositionType) AS composition_aggregator')
            ->addGroupBy('composition_aggregator');

        $qb->setParameter(
            'ondate_composition_type',
            $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 function ($value): string {
            if ('_header' === $value) {
                return 'Composition';
            }

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

            $c = $this->typeRepository->find($value);

            return $this->translatableStringHelper->localize(
                $c->getLabel()
            );
        };
    }

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

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