<?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\Repository\CenterRepositoryInterface;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class CenterAggregator implements AggregatorInterface
{
    private const COLUMN_NAME = 'person_center_aggregator';

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

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

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

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

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

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

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

            if ('_header' === $value) {
                return 'export.aggregator.person.by_center.center';
            }

            return (string) $this->centerRepository->find((int) $value)?->getName();
        };
    }

    public function getQueryKeys($data): array
    {
        return [self::COLUMN_NAME];
    }

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

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        $alias = 'pers_center_agg';
        $atDate = 'pers_center_agg_at_date';

        $qb->leftJoin('person.centerHistory', $alias);
        $qb
            ->andWhere(
                $qb->expr()->lte($alias.'.startDate', ':'.$atDate),
            )->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->isNull($alias.'.endDate'),
                    $qb->expr()->gt($alias.'.endDate', ':'.$atDate)
                )
            );
        $qb->setParameter($atDate, $this->rollingDateConverter->convert($data['at_date']));

        $qb->addSelect("IDENTITY({$alias}.center) AS ".self::COLUMN_NAME);
        $qb->addGroupBy(self::COLUMN_NAME);
    }

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