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

final readonly class MaritalStatusAggregator implements AggregatorInterface
{
    public function __construct(private MaritalStatusRepository $maritalStatusRepository, private TranslatableStringHelper $translatableStringHelper) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        if (!\in_array('personmarital', $qb->getAllAliases(), true)) {
            $qb->join('person.maritalStatus', 'personmarital');
        }

        $qb->addSelect('personmarital.id as marital_status_aggregator');
        $qb->addGroupBy('marital_status_aggregator');
    }

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

    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 'Marital status';
            }

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

            $g = $this->maritalStatusRepository->find($value);

            return $this->translatableStringHelper->localize($g->getName());
        };
    }

    public function getQueryKeys($data)
    {
        return ['marital_status_aggregator'];
    }

    public function getTitle()
    {
        return 'Group people by marital status';
    }
}
