<?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\CoreBundle\Cron;

use Contao\CoreBundle\Cron\Cron;
use Contao\CoreBundle\DependencyInjection\Attribute\AsCronJob;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Query\Expr\Join;
use Ferienpass\CoreBundle\Enum\AttendanceStatus;
use Ferienpass\CoreBundle\Enum\OfferStatus;
use Ferienpass\CoreBundle\Message\RemindAttendance;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Settings\SystemSettingsManager;
use Symfony\Component\Messenger\MessageBusInterface;

#[AsCronJob('hourly')]
class SendRemindersListener
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly MessageBusInterface $commandBus, private readonly SystemSettingsManager $systemSettingsManager)
    {
    }

    public function __invoke(string $scope): void
    {
        if (Cron::SCOPE_WEB === $scope) {
            return;
        }

        if (!$this->systemSettingsManager->isRemindAttendance()) {
            return;
        }

        // Notice period: defaults to 1.5 days (36 hours) when unset
        $noticePeriodStr = $this->systemSettingsManager->getAttendanceRemindPeriod() ?? '+36 hours';
        $noticePeriod = new \DateTimeImmutable($noticePeriodStr);
        $published = OfferStatus::PUBLISHED;
        $cancelled = OfferStatus::CANCELLED;

        $qb = $this->attendances->createQueryBuilder('a');

        // Subquery: Attendances being notified already
        $sub = $this->attendances->createQueryBuilder('a1')
            ->leftJoin('a1.messengerLogs', 'm', Join::WITH, 'm.message = :message')
            ->andWhere('m IS NOT NULL')
            ->addGroupBy('a1.id')
        ;

        $attendances = $qb
            ->innerJoin('a.offer', 'o')
            ->innerJoin('o.dates', 'd')
            ->groupBy('a.id')

            ->andWhere($qb->expr()->notIn('a.id', $sub->getDQL()))
            ->setParameter('message', RemindAttendance::class)

            ->andWhere('a.status = :status')
            ->setParameter('status', AttendanceStatus::CONFIRMED)

            ->andWhere("JSON_CONTAINS_PATH(o.status, 'one', '$.$published') = 1")
            ->andWhere("JSON_CONTAINS_PATH(o.status, 'one', '$.$cancelled') = 0")

            // The offer must not be in the past
            ->andHaving('MIN(d.begin) > CURRENT_TIMESTAMP()')

            // The offer must take place no earlier than the notice period
            ->andHaving('MIN(d.begin) <= :date')
            ->setParameter('date', $noticePeriod, Types::DATETIME_IMMUTABLE)

            ->getQuery()
            ->execute()
        ;

        // Group the due attendances by recipient so a parent with several
        // children (or one child in several offers) receives a single, combined
        // reminder instead of one mail per attendance. Only attendances due in
        // this run are grouped; a sibling whose offer enters the notice period
        // later still gets its own reminder then.
        $groups = [];
        foreach ($attendances as $attendance) {
            $email = (string) $attendance->getParticipant()?->getEmail();

            // Attendances without a resolvable recipient keep their own group,
            // preserving the previous one-message-per-attendance behaviour (the
            // handler no-ops on send, but the message is still logged as done).
            $key = '' !== $email ? 'e:'.mb_strtolower($email) : 'a:'.$attendance->getUuid()->toRfc4122();

            $groups[$key][] = (string) $attendance->getUuid();
        }

        foreach ($groups as $attendanceIds) {
            $this->commandBus->dispatch(new RemindAttendance(...$attendanceIds));
        }
    }
}
