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

use Chill\MainBundle\Export\FormatterInterface;
use Chill\MainBundle\Export\GroupedExportInterface;
use Chill\MainBundle\Export\Helper\AggregateStringHelper;
use Chill\MainBundle\Export\Helper\ExportAddressHelper;
use Chill\MainBundle\Export\Helper\TranslatableStringExportLabelHelper;
use Chill\MainBundle\Export\ListInterface;
use Chill\MainBundle\Form\Type\PickRollingDateType;
use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Service\RollingDate\RollingDateConverterInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Household\HouseholdComposition;
use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Chill\PersonBundle\Entity\Person\PersonCenterHistory;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Security\Authorization\HouseholdVoter;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormBuilderInterface;

class ListHouseholdInPeriod implements ListInterface, GroupedExportInterface
{
    private const FIELDS = [
        'id',
        'membersCount',
        'membersId',
        'membersName',
        'compositionNumberOfChildren',
        'compositionComment',
        'compositionType',
    ];
    private readonly bool $filterStatsByCenters;

    public function __construct(
        private readonly ExportAddressHelper $addressHelper,
        private readonly AggregateStringHelper $aggregateStringHelper,
        private readonly EntityManagerInterface $entityManager,
        private readonly RollingDateConverterInterface $rollingDateConverter,
        private readonly TranslatableStringExportLabelHelper $translatableStringHelper,
        ParameterBagInterface $parameterBag,
    ) {
        $this->filterStatsByCenters = $parameterBag->get('chill_main')['acl']['filter_stats_by_center'];
    }

    public function buildForm(FormBuilderInterface $builder)
    {
        $builder
            ->add('calc_date', PickRollingDateType::class, [
                'label' => 'export.list.household.Date of calculation for associated elements',
                'help' => 'export.list.household.help_description',
                'required' => true,
            ]);
    }

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

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

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

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

    public function getAllowedFormattersTypes()
    {
        return [FormatterInterface::TYPE_LIST];
    }

    public function getDescription(): string
    {
        return 'export.list.household.List description';
    }

    public function getGroup(): string
    {
        return 'Exports of households';
    }

    public function getLabels($key, array $values, $data)
    {
        if (str_starts_with($key, 'address_fields')) {
            return $this->addressHelper->getLabel($key, $values, $data, 'address_fields');
        }

        return match ($key) {
            'membersId', 'membersName' => $this->aggregateStringHelper->getLabelMulti($key, $values, 'export.list.household.'.$key),
            'compositionType' => $this->translatableStringHelper->getLabel($key, $values, 'export.list.household.'.$key),
            default => static function ($value) use ($key) {
                if ('_header' === $value) {
                    return 'export.list.household.'.$key;
                }

                return (string) $value;
            },
        };
    }

    public function getQueryKeys($data): array
    {
        return array_merge(
            self::FIELDS,
            $this->addressHelper->getKeys(ExportAddressHelper::F_ALL, 'address_fields')
        );
    }

    public function getResult($query, $data, \Chill\MainBundle\Export\ExportGenerationContext $context): array
    {
        return $query->getQuery()->getResult(AbstractQuery::HYDRATE_SCALAR);
    }

    public function getTitle(): string
    {
        return 'export.list.household.List household associated with accompanying period title';
    }

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

    public function initiateQuery(array $requiredModifiers, array $acl, array $data, \Chill\MainBundle\Export\ExportGenerationContext $context): QueryBuilder
    {
        $centers = array_map(static fn ($el) => $el['center'], $acl);

        $qb = $this->entityManager->createQueryBuilder();

        $qb
            ->from(Household::class, 'household')
            ->distinct()
            ->select('household.id AS id')
            ->join('household.members', 'hmember')
            ->join('hmember.person', 'person')
            ->join('person.accompanyingPeriodParticipations', 'acppart')
            ->join('acppart.accompanyingPeriod', 'acp')
            ->andWhere('acppart.startDate != acppart.endDate OR acppart.endDate IS NULL')
            ->andWhere('hmember.startDate <= :count_household_at_date AND (hmember.endDate IS NULL OR hmember.endDate > :count_household_at_date)')
            ->andWhere('acp.step != :list_acp_step')
            ->setParameter('count_household_at_date', $this->rollingDateConverter->convert($data['calc_date']))
            ->setParameter('list_acp_step', AccompanyingPeriod::STEP_DRAFT);

        if ($this->filterStatsByCenters) {
            $qb
                ->andWhere(
                    $qb->expr()->exists(
                        'SELECT 1 FROM '.PersonCenterHistory::class.' acl_count_person_history WHERE acl_count_person_history.person = person
                    AND acl_count_person_history.center IN (:authorized_centers)
                    '
                    )
                )
                ->setParameter('authorized_centers', $centers);
        }

        $this->addSelectClauses($qb, $this->rollingDateConverter->convert($data['calc_date']));

        return $qb;
    }

    public function requiredRole(): string
    {
        return HouseholdVoter::STATS;
    }

    public function supportsModifiers(): array
    {
        return [
            Declarations::HOUSEHOLD_TYPE,
            Declarations::ACP_TYPE,
            Declarations::PERSON_TYPE,
        ];
    }

    private function addSelectClauses(QueryBuilder $qb, \DateTimeImmutable $calcDate): void
    {
        // members at date
        $qb
            ->addSelect('(SELECT COUNT(members0) FROM '.HouseholdMember::class.' members0 '
                .'WHERE members0.startDate <= :calcDate AND (members0.endDate IS NULL OR members0.endDate > :calcDate) '
                .'AND members0 MEMBER OF household.members) AS membersCount')

            ->addSelect('(SELECT AGGREGATE(IDENTITY(members1.person)) FROM '.HouseholdMember::class.' members1 '
                .'WHERE members1.startDate <= :calcDate AND (members1.endDate IS NULL OR members1.endDate > :calcDate) '
                .'AND members1 MEMBER OF household.members) AS membersId')

            ->addSelect("(SELECT AGGREGATE(CONCAT(person2.firstName, ' ', person2.lastName)) FROM ".HouseholdMember::class.' members2 '
                .'JOIN members2.person person2 '
                .'WHERE members2.startDate <= :calcDate AND (members2.endDate IS NULL OR members2.endDate > :calcDate) '
                .'AND members2 MEMBER OF household.members) AS membersName');

        // composition at date
        $qb
            ->addSelect('(SELECT compo.numberOfChildren FROM '.HouseholdComposition::class.' compo '
                .'WHERE compo.startDate <= :calcDate AND (compo.endDate IS NULL OR compo.endDate > :calcDate) '
                .'AND compo MEMBER OF household.compositions) AS compositionNumberOfChildren')

            ->addSelect('(SELECT compo1.comment.comment FROM '.HouseholdComposition::class.' compo1 '
                .'WHERE compo1.startDate <= :calcDate AND (compo1.endDate IS NULL OR compo1.endDate > :calcDate) '
                .'AND compo1 MEMBER OF household.compositions) AS compositionComment')

            ->addSelect('(
                SELECT type2.label
                FROM '.HouseholdComposition::class.' compo2
                JOIN compo2.householdCompositionType type2
                WHERE compo2.startDate <= :calcDate AND (compo2.endDate IS NULL OR compo2.endDate > :calcDate)
                AND compo2 MEMBER OF household.compositions
            ) AS compositionType');

        // address at date
        $qb
            ->leftJoin('household.addresses', 'addresses')
            ->andWhere(
                $qb->expr()->orX(
                    $qb->expr()->isNull('addresses'), // Include households without any address
                    $qb->expr()->andX(
                        $qb->expr()->lte('addresses.validFrom', ':calcDate'),
                        $qb->expr()->orX(
                            $qb->expr()->isNull('addresses.validTo'),
                            $qb->expr()->gt('addresses.validTo', ':calcDate')
                        )
                    )
                )
            );
        $this->addressHelper->addSelectClauses(
            ExportAddressHelper::F_ALL,
            $qb,
            'addresses',
            'address_fields'
        );

        // inject date parameter
        $qb->setParameter('calcDate', $calcDate);
    }
}
