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

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

final readonly class DurationAggregator implements AggregatorInterface
{
    private const CHOICES = [
        'month',
        'week',
        'day',
    ];

    public function __construct(private TranslatorInterface $translator) {}

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

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        match ($data['precision']) {
            'day' => $qb->addSelect('(COALESCE(acp.closingDate, :now) - acp.openingDate)  AS duration_aggregator'),
            'week' => $qb->addSelect('(COALESCE(acp.closingDate, :now) - acp.openingDate) / 7  AS duration_aggregator'),
            'month' => $qb->addSelect('(EXTRACT (YEAR FROM AGE(COALESCE(acp.closingDate, :now), acp.openingDate)) * 12 +
                    EXTRACT (MONTH FROM AGE(COALESCE(acp.closingDate, :now), acp.openingDate))) AS duration_aggregator'),
            default => throw new \LogicException('precision not supported: '.$data['precision']),
        };

        $qb
            ->setParameter('now', new \DateTimeImmutable('now'))
            ->addGroupBy('duration_aggregator')
            ->addOrderBy('duration_aggregator');
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('precision', ChoiceType::class, [
            'choices' => array_combine(self::CHOICES, self::CHOICES),
            'label' => 'export.aggregator.course.duration.Precision',
            'choice_label' => static fn (string $c) => 'export.aggregator.course.duration.'.$c,
            'multiple' => false,
            'expanded' => true,
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['precision' => $formData['precision']];
    }

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return static function ($value) use ($data) {
            if ('_header' === $value) {
                return 'export.aggregator.course.duration.'.$data['precision'];
            }

            if (null === $value) {
                return 0;
            }

            return $value;
        };
    }

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

    public function getTitle(): string
    {
        return 'Group by duration';
    }
}
