<?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 Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Notifier\TexterInterface;

class BulkCalendarShortMessageSender
{
    public function __construct(
        private readonly CalendarForShortMessageProvider $provider,
        private readonly EntityManagerInterface $em,
        private readonly LoggerInterface $logger,
        private readonly TexterInterface $texter,
        private readonly ShortMessageForCalendarBuilderInterface $messageForCalendarBuilder,
    ) {}

    public function sendBulkMessageToEligibleCalendars()
    {
        $countCalendars = 0;
        $countSms = 0;

        foreach ($this->provider->getCalendars(new \DateTimeImmutable('now')) as $calendar) {
            $smses = $this->messageForCalendarBuilder->buildMessageForCalendar($calendar);

            foreach ($smses as $sms) {
                $this->texter->send($sms);
                ++$countSms;
            }

            $this->em
                ->createQuery('UPDATE '.Calendar::class.' c SET c.smsStatus = :smsStatus WHERE c.id = :id')
                ->setParameters(['smsStatus' => Calendar::SMS_SENT, 'id' => $calendar->getId()])
                ->execute();
            ++$countCalendars;
            $this->em->refresh($calendar);
        }

        $this->logger->info(self::class.'a bulk of messages was sent', ['count_calendars' => $countCalendars, 'count_sms' => $countSms]);
    }
}
