<?php

/**
 * 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.
 */

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\CalendarBundle\Service\ShortMessageNotification;

use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Repository\CalendarRepository;
use Doctrine\ORM\EntityManagerInterface;

class CalendarForShortMessageProvider
{
    public function __construct(
        private readonly CalendarRepository $calendarRepository,
        private readonly EntityManagerInterface $em,
        private readonly RangeGeneratorInterface $rangeGenerator,
    ) {}

    /**
     * Generate calendars instance.
     *
     * Warning: this method takes care of clearing the EntityManager at regular interval
     *
     * @return iterable|Calendar[]
     */
    public function getCalendars(\DateTimeImmutable $at): iterable
    {
        $range = $this->rangeGenerator->generateRange($at);

        if (null === $range) {
            return;
        }

        ['startDate' => $startDate, 'endDate' => $endDate] = $range;

        $offset = 0;
        $batchSize = 10;

        $calendars = $this->calendarRepository
            ->findByNotificationAvailable($startDate, $endDate, $batchSize, $offset);

        do {
            foreach ($calendars as $calendar) {
                ++$offset;

                yield $calendar;
            }

            $this->em->clear();

            $calendars = $this->calendarRepository
                ->findByNotificationAvailable($startDate, $endDate, $batchSize, $offset);
        } while (\count($calendars) === $batchSize);
    }
}
