<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Application\ExclusionReasons;

use Ferienpass\CmsBundle\Application\ExclusionReasonEvent;
use Ferienpass\CoreBundle\ApplicationSystem\FirstComeApplicationSystem;
use Ferienpass\CoreBundle\Entity\Attendance;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Translation\TranslatableMessage;

#[AsEventListener]
class DayLimitReachedListener
{
    public function __invoke(ExclusionReasonEvent $event): void
    {
        $offer = $event->getOffer();
        $participant = $event->getParticipant();
        $applicationSystem = $event->getApplicationSystem();

        if (!$applicationSystem instanceof FirstComeApplicationSystem) {
            return;
        }

        $task = $applicationSystem->getTask();
        if (!$task || !$limit = $task->getMaxApplicationsDay()) {
            return;
        }

        $today = new \DateTimeImmutable();
        $dayBegin = new \DateTimeImmutable($today->format('Y-m-d 00:00'));
        $dayEnd = new \DateTimeImmutable($today->format('Y-m-d 23:59:59'));

        $attendances = $participant
            ->getAttendances()
            ->filter(static fn (Attendance $a) => $a->getTask()?->getId() === $task->getId() && $a->getCreatedAt() >= $dayBegin && $a->getCreatedAt() <= $dayEnd)
        ;

        if (\count($attendances) >= $limit) {
            throw new DayLimitReached($offer, $participant, new TranslatableMessage('ineligible.dayLimitReached', ['name' => $participant->getFirstname(), 'max' => $task->getMaxApplicationsDay()]));
        }
    }
}
