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

use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Repository\UserRepository;
use Chill\MainBundle\Templating\Entity\UserRender;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class CreatorAggregator implements AggregatorInterface
{
    private const PREFIX = 'acpw_aggr_creator';

    public function __construct(
        private readonly UserRepository $userRepository,
        private readonly UserRender $userRender,
    ) {}

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

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

        $qb
            ->addSelect("IDENTITY(acpw.createdBy) AS {$p}_select")
            ->addGroupBy("{$p}_select");
    }

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

    public function buildForm(FormBuilderInterface $builder): void {}

    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
    {
        return function ($value): string {
            if ('_header' === $value) {
                return 'export.aggregator.course_work.by_creator.Creator';
            }

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

            $r = $this->userRepository->find($value);

            return $this->userRender->renderString($r, ['absence' => false, 'user_job' => false, 'main_scope' => false]);
        };
    }

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

    public function getTitle(): string
    {
        return 'export.aggregator.course_work.by_creator.title';
    }
}
