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

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\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class AccompanyingPeriodWorkEndDateBetweenDateFilter implements FilterInterface
{
    public function __construct(
        private RollingDateConverterInterface $rollingDateConverter,
    ) {}

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder
            ->add('start_date', PickRollingDateType::class, [
                'label' => 'export.filter.work.end_between_dates.start_date',
            ])
            ->add('end_date', PickRollingDateType::class, [
                'label' => 'export.filter.work.end_between_dates.end_date',
            ])
            ->add('keep_null', CheckboxType::class, [
                'label' => 'export.filter.work.end_between_dates.keep_null',
                'help' => 'export.filter.work.end_between_dates.keep_null_help',
            ]);
    }

    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(), 'keep_null' => $formData['keep_null']];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return [
            'start_date' => RollingDate::fromNormalized($formData['start_date']),
            'end_date' => RollingDate::fromNormalized($formData['end_date']),
            'keep_null' => (bool) ($formData['keep_null'] ?? true),
        ];
    }

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

    public function getTitle(): string
    {
        return 'export.filter.work.end_between_dates.title';
    }

    public function describeAction($data, ExportGenerationContext $context): array
    {
        return [
            'export.filter.work.end_between_dates.Only where start date is between %startDate% and %endDate%',
            [
                '%startDate%' => null !== $data['start_date'] ? $this->rollingDateConverter->convert($data['start_date'])->format('d-m-Y') : '',
                '%endDate%' => null !== $data['end_date'] ? $this->rollingDateConverter->convert($data['end_date'])->format('d-m-Y') : '',
            ],
        ];
    }

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

    public function alterQuery(QueryBuilder $qb, $data, ExportGenerationContext $exportGenerationContext): void
    {
        $as = 'acc_pe_work_end_between_filter_start';
        $ae = 'acc_pe_work_end_between_filter_end';

        $start = match ($data['keep_null']) {
            true => $qb->expr()->orX(
                $qb->expr()->lte('acpw.endDate', ':'.$ae),
                $qb->expr()->isNull('acpw.endDate')
            ),
            false => $qb->expr()->andX(
                $qb->expr()->lte('acpw.endDate', ':'.$ae),
                $qb->expr()->isNotNull('acpw.endDate')
            ),
            default => throw new \LogicException('This value is not supported'),
        };
        $end = match ($data['keep_null']) {
            true => $qb->expr()->orX(
                $qb->expr()->gt('COALESCE(acp.closingDate, acpw.endDate)', ':'.$as),
                $qb->expr()->isNull('acpw.endDate')
            ),
            false => $qb->expr()->andX(
                $qb->expr()->gt('COALESCE(acp.closingDate, acpw.endDate)', ':'.$as),
                $qb->expr()->isNotNull('acpw.endDate')
            ),
            default => throw new \LogicException('This value is not supported'),
        };

        if (null !== $data['start_date']) {
            $qb
                ->andWhere($start)
                ->setParameter($as, $this->rollingDateConverter->convert($data['start_date']));
        }

        if (null !== $data['end_date']) {
            $qb
                ->andWhere($end)
                ->setParameter($ae, $this->rollingDateConverter->convert($data['end_date']));
        }
    }

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