<?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\ExportInterface;
use Chill\MainBundle\Export\FormatterInterface;
use Chill\MainBundle\Export\GroupedExportInterface;
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\Person\PersonCenterHistory;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Security\Authorization\HouseholdVoter;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormBuilderInterface;

class CountHouseholdInPeriod implements ExportInterface, GroupedExportInterface
{
    private const TR_PREFIX = 'export.export.nb_household_with_course.';
    private readonly bool $filterStatsByCenters;

    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly RollingDateConverterInterface $rollingDateConverter,
        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' => self::TR_PREFIX.'Date of calculation of household members',
                'required' => false,
            ]);
    }

    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(): array
    {
        return [FormatterInterface::TYPE_TABULAR];
    }

    public function getDescription(): string
    {
        return self::TR_PREFIX.'Count household with accompanying course by various parameters.';
    }

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

    public function getLabels($key, array $values, $data)
    {
        return static function ($value) use ($key) {
            if ('_header' === $value) {
                return match ($key) {
                    'household_export_result' => self::TR_PREFIX.'Count households',
                    'acp_export_result' => self::TR_PREFIX.'Count accompanying periods',
                    default => throw new \LogicException('Key not supported: '.$key),
                };
            }

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

            return $value;
        };
    }

    public function getQueryKeys($data): array
    {
        return ['household_export_result', 'acp_export_result'];
    }

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

    public function getTitle(): string
    {
        return self::TR_PREFIX.'Count households with accompanying course';
    }

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

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

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

        $qb
            ->from(Household::class, 'household')
            ->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 != :count_acp_step')
            ->setParameter('count_household_at_date', $this->rollingDateConverter->convert($data['calc_date']))
            ->setParameter('count_acp_step', AccompanyingPeriod::STEP_DRAFT);

        $qb
            ->select('COUNT(DISTINCT household.id) AS household_export_result')
            ->addSelect('COUNT(DISTINCT acp.id) AS acp_export_result');

        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);
        }

        return $qb;
    }

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

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