<?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\Filter\HouseholdFilters;

use Chill\MainBundle\Export\ExportGenerationContext;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Entity\Household\HouseholdCompositionType;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Repository\Household\HouseholdCompositionTypeRepositoryInterface;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormBuilderInterface;

readonly class CompositionFilter implements FilterInterface
{
    use \Chill\MainBundle\Export\ExportDataNormalizerTrait;

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

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        // there is no test on the aliases here: the name should be unique
        $clause =
            $qb->expr()->andX(
                $qb->expr()->lte('composition_type_filter_composition.startDate', ':ondate_composition_type_filter'),
                $qb->expr()->orX(
                    $qb->expr()->gt('composition_type_filter_composition.endDate', ':ondate_composition_type_filter'),
                    $qb->expr()->isNull('composition_type_filter_composition.endDate')
                )
            );

        $qb->join('household.compositions', 'composition_type_filter_composition', Expr\Join::WITH, $clause);

        $whereClause = $qb->expr()->in('composition_type_filter_composition.householdCompositionType', ':compositions_composition_type_filter');

        $qb->andWhere($whereClause);
        $qb->setParameter('compositions_composition_type_filter', $data['accepted_composition']);
        $qb->setParameter(
            'ondate_composition_type_filter',
            $this->rollingDateConverter->convert($data['on_date'])
        );
    }

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

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('accepted_composition', EntityType::class, [
                'class' => HouseholdCompositionType::class,
                'choice_label' => fn (HouseholdCompositionType $type) => $this->translatableStringHelper->localize(
                    $type->getLabel()
                ),
                'multiple' => true,
                'expanded' => true,
            ])
            ->add('on_date', PickRollingDateType::class, []);
    }

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

    public function normalizeFormData(array $formData): array
    {
        return ['accepted_composition' => $this->normalizeDoctrineEntity($formData['accepted_composition']), 'on_date' => $formData['on_date']->normalize()];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return ['accepted_composition' => $this->denormalizeDoctrineEntity($formData['accepted_composition'], $this->householdCompositionTypeRepository), 'on_date' => RollingDate::fromNormalized($formData['on_date'])];
    }

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

    public function describeAction($data, ExportGenerationContext $context): array
    {
        $compositions = [];

        foreach ($data['accepted_composition'] as $c) {
            $compositions[] = $this->translatableStringHelper->localize(
                $c->getLabel()
            );
        }

        return ['Filtered by composition: only %compositions% on %ondate%', [
            '%compositions%' => implode(', ', $compositions),
            '%ondate%' => $this->rollingDateConverter->convert($data['on_date'])->format('d-m-Y'),
        ]];
    }

    public function getTitle(): string
    {
        return 'Filter by composition';
    }
}
