<?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\ActivityBundle\Export\Aggregator;

use Chill\ActivityBundle\Export\Declarations;
use Chill\ActivityBundle\Tests\Export\Aggregator\PersonsAggregatorTest;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\PersonBundle\Export\Helper\LabelPersonHelper;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @see PersonsAggregatorTest
 */
final readonly class PersonsAggregator implements AggregatorInterface
{
    private const PREFIX = 'act_persons_agg';

    public function __construct(private LabelPersonHelper $labelPersonHelper) {}

    public function buildForm(FormBuilderInterface $builder): void
    {
        // nothing to add here
    }

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

    public function normalizeFormData(array $formData): array
    {
        return [];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return [];
    }

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function getLabels($key, array $values, mixed $data): callable
    {
        if ($key !== self::PREFIX.'_pid') {
            throw new \UnexpectedValueException('this key should not be handled: '.$key);
        }

        return $this->labelPersonHelper->getLabel($key, $values, 'export.aggregator.activity.by_persons.Persons');
    }

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

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.aggregator.activity.by_persons.Group activity by persons';
    }

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

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

        $qb
            ->leftJoin('activity.persons', "{$p}_p")
            ->addSelect("{$p}_p.id AS {$p}_pid")
            ->addGroupBy("{$p}_pid");
    }

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