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

use Chill\ActivityBundle\Export\Declarations;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\PersonBundle\Repository\SocialWork\SocialIssueRepository;
use Chill\PersonBundle\Templating\Entity\SocialIssueRender;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class BySocialIssueAggregator implements AggregatorInterface
{
    public function __construct(private readonly SocialIssueRepository $issueRepository, private readonly SocialIssueRender $issueRender) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        if (!\in_array('actsocialissue', $qb->getAllAliases(), true)) {
            $qb->leftJoin('activity.socialIssues', 'actsocialissue');
        }

        $qb->addSelect('actsocialissue.id AS socialissue_aggregator');
        $qb->addGroupBy('socialissue_aggregator');
    }

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

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

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

    public function getLabels($key, array $values, $data)
    {
        return function ($value): string {
            if ('_header' === $value) {
                return 'Social issues';
            }

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

            $i = $this->issueRepository->find($value);

            return $this->issueRender->renderString($i, []);
        };
    }

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

    public function getTitle(): string
    {
        return 'Group activity by linked socialissue';
    }
}
