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

use Chill\MainBundle\Export\AggregatorInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class HavingEndDateAggregator implements AggregatorInterface
{
    public function __construct(private readonly TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data): void
    {
        $qb
            ->addSelect('CASE WHEN workeval.endDate IS NULL THEN true ELSE false END AS eval_enddate_aggregator')
            ->addGroupBy('eval_enddate_aggregator');
    }

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

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

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

    public function getLabels($key, array $values, $data)
    {
        return function ($value): string {
            if ('_header' === $value) {
                return 'export.aggregator.eval.by_end_date.Has end date ?';
            }

            return match ($value) {
                true => $this->translator->trans('export.aggregator.eval.by_end_date.enddate is specified'),
                false => $this->translator->trans('export.aggregator.eval.by_end_date.enddate is not specified'),
                default => throw new \LogicException(sprintf('The value %s is not valid', $value)),
            };
        };
    }

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

    public function getTitle(): string
    {
        return 'export.aggregator.eval.by_end_date.Group evaluations having end date';
    }
}
