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

use Chill\MainBundle\Service\RollingDate\RollingDate;
use Chill\MainBundle\Test\Export\AbstractFilterTest;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Household\HouseholdCompositionType;
use Chill\PersonBundle\Export\Filter\HouseholdFilters\CompositionFilter;
use Doctrine\ORM\EntityManagerInterface;

/**
 * @internal
 *
 * @coversNothing
 */
final class CompositionFilterTest extends AbstractFilterTest
{
    private CompositionFilter $filter;

    protected function setUp(): void
    {
        self::bootKernel();

        $this->filter = self::getContainer()->get('chill.person.export.filter_household_composition');
    }

    public function getFilter(): CompositionFilter
    {
        return $this->filter;
    }

    public static function getFormData(): array
    {
        self::bootKernel();
        $em = self::getContainer()->get(EntityManagerInterface::class);
        $array = $em->createQueryBuilder()
            ->from(HouseholdCompositionType::class, 'r')
            ->select('r')
            ->getQuery()
            ->setMaxResults(1)
            ->getResult();
        $data = [];
        foreach ($array as $r) {
            $data[] = [
                'accepted_composition' => $r,
                'on_date' => new RollingDate(RollingDate::T_TODAY),
            ];
        }

        return $data;
    }

    public static function getQueryBuilders(): iterable
    {
        self::bootKernel();
        $em = self::getContainer()->get(EntityManagerInterface::class);
        $qb = $em->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)')
            ->setParameter('count_household_at_date', new \DateTimeImmutable('today'));
        $qb
            ->select('COUNT(DISTINCT household.id) AS household_export_result')
            ->addSelect('COUNT(DISTINCT acp.id) AS acp_export_result');
        yield $qb;
    }
}
