<?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\Entity\User\UserJobHistory;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Export\DataTransformerInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Repository\UserJobRepository;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class UserJobAggregator implements AggregatorInterface, DataTransformerInterface
{
    private const PREFIX = 'acp_agg_user_job';

    public function __construct(
        private UserJobRepository $jobRepository,
        private TranslatableStringHelper $translatableStringHelper,
        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(
                'acp.userHistories',
                "{$p}_userHistory",
                Join::WITH,
                $qb->expr()->andX(
                    $qb->expr()->eq("{$p}_userHistory.accompanyingPeriod", 'acp.id'),
                    // check that the user is referrer when the accompanying period is opened
                    "OVERLAPSI (acp.openingDate, acp.closingDate), ({$p}_userHistory.startDate, {$p}_userHistory.endDate) = TRUE",
                    "OVERLAPSI (:{$p}_startDate, :{$p}_endDate), ({$p}_userHistory.startDate, {$p}_userHistory.endDate) = TRUE"
                )
            )
            ->leftJoin(
                UserJobHistory::class,
                "{$p}_jobHistory",
                Join::WITH,
                $qb->expr()->andX(
                    "{$p}_jobHistory.user = {$p}_userHistory.user",
                    "OVERLAPSI ({$p}_jobHistory.startDate, {$p}_jobHistory.endDate), ({$p}_userHistory.startDate, {$p}_userHistory.endDate) = TRUE",
                    "OVERLAPSI (:{$p}_startDate, :{$p}_endDate), ({$p}_jobHistory.startDate, {$p}_jobHistory.endDate) = TRUE"
                )
            )
            ->setParameter("{$p}_startDate", $this->rollingDateConverter->convert($data['start_date']))
            ->setParameter("{$p}_endDate", $this->rollingDateConverter->convert($data['end_date']))
            ->addSelect("IDENTITY({$p}_jobHistory.job) AS {$p}_select")
            ->addGroupBy("{$p}_select");
    }

    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_job.Referrer and job after',
                'required' => true,
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.aggregator.course.by_referrer_job.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
    {
        return ['start_date' => RollingDate::fromNormalized($formData['start_date']), 'end_date' => RollingDate::fromNormalized($formData['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 = [];

        $data['start_date'] = $before['start_date'] ?? new RollingDate(RollingDate::T_FIXED_DATE, new \DateTimeImmutable('1970-01-01'));
        $data['end_date'] = $before['end_date'] ?? $default['end_date'];

        return $data;
    }

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

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

            if (null === $j = $this->jobRepository->find($value)) {
                return '';
            }

            return $this->translatableStringHelper->localize(
                $j->getLabel()
            );
        };
    }

    public function getQueryKeys($data): array
    {
        return [self::PREFIX.'_select'];
    }

    public function getTitle(): string
    {
        return 'export.aggregator.course.by_user_job.Group by user job';
    }
}
