<?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\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\UserRepository;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class ReferrerAggregator implements AggregatorInterface
{
    private const PREFIX = 'acpw_referrer_aggregator';

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

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

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

        $qb
            ->leftJoin('acpw.referrersHistory', $p.'_acpwusers_history')
            ->andWhere("{$p}_acpwusers_history.startDate <= :{$p}_calc_date AND ({$p}_acpwusers_history.endDate IS NULL or {$p}_acpwusers_history.endDate > :{$p}_calc_date)");

        $qb->setParameter("{$p}_calc_date", $this->rollingDateConverter->convert(
            $data['referrer_at'] ?? new RollingDate(RollingDate::T_TODAY)
        ));
        $qb->addSelect("IDENTITY({$p}_acpwusers_history.user) AS referrer_aggregator");
        $qb->addGroupBy('referrer_aggregator');
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('referrer_at', PickRollingDateType::class, [
            'label' => 'export.aggregator.course_work.by_treating_agent.Calc date',
        ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        if (!array_key_exists('referrer_at', $formData)) {
            return ['referrer_at' => (new RollingDate(RollingDate::T_TODAY))->normalize()];
        }

        return ['referrer_at' => $formData['referrer_at']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        if (!array_key_exists('referrer_at', $formData)) {
            return ['referrer_at' => new RollingDate(RollingDate::T_TODAY)];
        }

        return ['referrer_at' => RollingDate::fromNormalized($formData['referrer_at'])];
    }

    public function getFormDefaultData(): array
    {
        return [
            'referrer_at' => new RollingDate(RollingDate::T_TODAY),
        ];
    }

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

            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 ['referrer_aggregator'];
    }

    public function getTitle(): string
    {
        return 'export.aggregator.course_work.by_treating_agent.Group by treating agent';
    }
}
