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

use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\Household\HouseholdComposition;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Repository\Household\HouseholdCompositionTypeRepositoryInterface;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class ByHouseholdCompositionAggregator implements AggregatorInterface
{
    private const PREFIX = 'acp_by_household_compo_agg';

    public function __construct(private readonly RollingDateConverterInterface $rollingDateConverter, private readonly HouseholdCompositionTypeRepositoryInterface $householdCompositionTypeRepository, private readonly TranslatableStringHelperInterface $translatableStringHelper) {}

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

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

        $qb
            ->leftJoin(
                'person.householdParticipations',
                "{$p}_hm"
            )
            ->leftJoin(
                HouseholdComposition::class,
                "{$p}_compo",
                Join::WITH,
                $qb->expr()->eq("{$p}_hm.household", "{$p}_compo.household"),
            )
            ->andWhere("{$p}_hm.startDate <= :{$p}_date AND ({$p}_hm.endDate IS NULL OR {$p}_hm.endDate > :{$p}_date)")
            ->andWhere("{$p}_hm.shareHousehold = 'TRUE'")
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->isNull("{$p}_compo"),
                    $qb->expr()->andX(
                        $qb->expr()->lte("{$p}_compo.startDate", ":{$p}_date"),
                        $qb->expr()->orX(
                            $qb->expr()->isNull("{$p}_compo.endDate"),
                            $qb->expr()->gt("{$p}_compo.endDate", ":{$p}_date")
                        )
                    )
                )
            )
            ->addSelect("IDENTITY({$p}_compo.householdCompositionType) AS {$p}_select")
            ->setParameter(
                "{$p}_date",
                $this->rollingDateConverter->convert($data['date_calc'])
            )
            ->addGroupBy("{$p}_select");
    }

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

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

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

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

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

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

    public function getLabels($key, array $values, $data): callable
    {
        return function ($value) {
            if ('_header' === $value) {
                return 'export.aggregator.person.by_household_composition.Household composition';
            }

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

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

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

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

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.aggregator.person.by_household_composition.Group course by household composition';
    }
}
