<?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\AccompanyingCourseExportHelper;
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\Person\PersonCenterHistory;
use Chill\PersonBundle\Export\Declarations;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class StatAccompanyingCourseDuration implements ExportInterface, GroupedExportInterface
{
    private readonly EntityRepository $repository;

    private bool $filterStatsByCenters;

    public function __construct(
        EntityManagerInterface $em,
        private RollingDateConverterInterface $rollingDateConverter,
        ParameterBagInterface $parameterBag,
    ) {
        $this->repository = $em->getRepository(AccompanyingPeriod::class);
        $this->filterStatsByCenters = $parameterBag->get('chill_main')['acl']['filter_stats_by_center'];
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        $builder->add('closingdate_rolling', PickRollingDateType::class, [
            'label' => 'Closingdate to apply',
        ]);
    }

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

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

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

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

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

    public function getDescription(): string
    {
        return 'Create an average of accompanying courses duration of each person participation to accompanying course, according to filters on persons, accompanying course';
    }

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

    public function getLabels($key, array $values, $data)
    {
        return static function ($value) use ($key) {
            if ('_header' === $value) {
                return match ($key) {
                    'avg_export_result' => 'export.export.acp_stats.avg_duration',
                    'count_acppart_export_result' => 'export.export.acp_stats.count_participations',
                    'count_acp_export_result' => 'export.export.acp_stats.count_acps',
                    'count_pers_export_result' => 'export.export.acp_stats.count_persons',
                    default => throw new \LogicException('key not supported: '.$key),
                };
            }

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

            return $value;
        };
    }

    public function getQueryKeys($data): array
    {
        return ['avg_export_result', 'count_acp_export_result', 'count_acppart_export_result', 'count_pers_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 'Accompanying courses participation duration and number of participations';
    }

    public function getType(): string
    {
        return Declarations::ACP_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->repository->createQueryBuilder('acp');

        $qb
            ->select('AVG(
                LEAST(acppart.endDate, COALESCE(acp.closingDate, :force_closingDate))
                - GREATEST(acppart.startDate, COALESCE(acp.openingDate, :force_closingDate))
            ) AS avg_export_result')
            ->addSelect('COUNT(DISTINCT acppart.id) AS count_acppart_export_result')
            ->addSelect('COUNT(DISTINCT person.id) AS count_pers_export_result')
            ->addSelect('COUNT(DISTINCT acp.id) AS count_acp_export_result')
            ->setParameter('force_closingDate', $this->rollingDateConverter->convert($data['closingdate_rolling']))
            ->leftJoin('acp.participations', 'acppart')
            ->leftJoin('acppart.person', 'person')
            ->andWhere('acp.step != :count_acp_step')
            ->andWhere('acppart.startDate != acppart.endDate OR acppart.endDate IS NULL')
            ->setParameter('count_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);
        }

        AccompanyingCourseExportHelper::addClosingMotiveExclusionClause($qb);

        return $qb;
    }

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

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