<?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\MainBundle\Notification\Email;

use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Chill\MainBundle\Notification\Email\NotificationEmailMessages\ScheduleDailyNotificationDigestMessage;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\MessageBusInterface;

readonly class DailyNotificationDigestCronjob implements CronJobInterface
{
    public function __construct(
        private ClockInterface $clock,
        private Connection $connection,
        private MessageBusInterface $messageBus,
        private LoggerInterface $logger,
    ) {}

    public function canRun(?CronJobExecution $cronJobExecution): bool
    {
        $now = $this->clock->now();

        if (null !== $cronJobExecution && $now->sub(new \DateInterval('PT23H45M')) < $cronJobExecution->getLastStart()) {
            return false;
        }

        // Run between 6 and 9 AM
        return in_array((int) $now->format('H'), [6, 7, 8], true);
    }

    public function getKey(): string
    {
        return 'daily-notification-digest';
    }

    /**
     * @throws \DateInvalidOperationException
     * @throws Exception
     */
    public function run(array $lastExecutionData): ?array
    {
        $now = $this->clock->now();

        if (isset($lastExecutionData['last_execution'])) {
            $lastExecution = \DateTimeImmutable::createFromFormat(
                \DateTimeImmutable::ATOM,
                $lastExecutionData['last_execution']
            );

            if (false === $lastExecution) {
                $lastExecution = $now->sub(new \DateInterval('P1D'));
            }
        } else {
            $lastExecution = $now->sub(new \DateInterval('P1D'));
        }

        // Get distinct users who received notifications since the last execution
        $sql = <<<'SQL'
        SELECT DISTINCT cmnau.user_id
        FROM chill_main_notification cmn
        JOIN chill_main_notification_addresses_user cmnau ON cmnau.notification_id = cmn.id
        WHERE cmn.date >= :lastExecution AND cmn.date <= :now
        SQL;

        $sqlStatement = $this->connection->prepare($sql);
        $sqlStatement->bindValue('lastExecution', $lastExecution->format(\DateTimeInterface::RFC3339));
        $sqlStatement->bindValue('now', $now->format(\DateTimeInterface::RFC3339));
        $result = $sqlStatement->executeQuery();

        $count = 0;
        foreach ($result->fetchAllAssociative() as $row) {
            $userId = (int) $row['user_id'];

            $message = new ScheduleDailyNotificationDigestMessage(
                $userId,
                $lastExecution,
                $now
            );

            $this->messageBus->dispatch($message);
            ++$count;
        }

        $this->logger->info('[DailyNotificationDigestCronjob] Dispatched daily digest messages', [
            'user_count' => $count,
            'last_execution' => $lastExecution->format('Y-m-d-H:i:s.u e'),
            'current_time' => $now->format('Y-m-d-H:i:s.u e'),
        ]);

        return [
            'last_execution' => $now->format(\DateTimeInterface::ATOM),
        ];
    }
}
