<?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\MainBundle\Export\DataTransformerInterface;
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, DataTransformerInterface
{
    private const A = 'acp_ref_agg_uhistory';

    private const P = 'acp_ref_agg_date';

    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
    {
        $qb
            ->addSelect('IDENTITY('.self::A.'.user) AS referrer_aggregator')
            ->addGroupBy('referrer_aggregator')
            ->leftJoin('acp.userHistories', self::A)
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->isNull(self::A),
                    $qb->expr()->andX(
                        $qb->expr()->lt(self::A.'.startDate', ':'.self::P.'_end_date'),
                        $qb->expr()->orX(
                            $qb->expr()->isNull(self::A.'.endDate'),
                            $qb->expr()->gte(self::A.'.endDate', ':'.self::P.'_start_date')
                        )
                    )
                )
            )
            ->setParameter(':'.self::P.'_end_date', $this->rollingDateConverter->convert($data['end_date']))
            ->setParameter(':'.self::P.'_start_date', $this->rollingDateConverter->convert($data['end_date']));
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.aggregator.course.by_referrer.Referrer after',
                'required' => true,
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.aggregator.course.by_referrer.Until',
                'required' => true,
            ]);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['start_date' => $formData['start_date']->normalize(), 'end_date' => $formData['end_date']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        $defaultData = $this->getFormDefaultData();

        return [
            'start_date' => array_key_exists('start_date', $formData) ? RollingDate::fromNormalized($formData['start_date']) : $defaultData['start_date'],
            'end_date' => array_key_exists('end_date', $formData) ? RollingDate::fromNormalized($formData['end_date']) : $defaultData['end_date'],
        ];
    }

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

    public function transformData(?array $before): array
    {
        $default = $this->getFormDefaultData();
        $data = [];

        if (null === $before) {
            return $default;
        }

        $data['start_date'] = $before['date_calc'] ?? $before['start_date'] ?? $default['start_date'];
        $data['end_date'] = $before['date_calc'] ?? $before['end_date'] ?? $default['end_date'];

        return $data;
    }

    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, []);
        };
    }

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

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