<?php
/**
 * BookiFlex Notification Extension
 *
 * @package    BookiFlex
 * @subpackage Notification
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Extensions\Notification\Service\Jobs;

use BookiFlex\Core\Contract\Queue\QueueJobInterface;
use BookiFlex\Extensions\Notification\Repository\NotificationRepository;
use BookiFlex\Extensions\Notification\Service\NotificationHandler;
use Psr\Log\LoggerInterface;

defined( 'ABSPATH' ) || exit;

/**
 * Recurring polling job that finds due notifications and sends them.
 *
 * Runs every 60 seconds via Action Scheduler.
 * Queries for PENDING notifications with send_time <= NOW() and attempt < MAX_ATTEMPTS.
 */
class PollDueNotificationsJob implements QueueJobInterface
{
    public const HOOK = 'bookiflex_poll_notifications';

    public function __construct(
        private readonly NotificationRepository $notificationRepository,
        private readonly NotificationHandler $notificationHandler,
        private readonly ?LoggerInterface $logger = null
    ) {
    }

    public function handle(array $args): void
    {
        $due = $this->notificationRepository->findDue();

        if (empty($due)) {
            $this->logger?->debug('PollDueNotificationsJob: no due notifications found');
            return;
        }

        $this->logger?->debug('PollDueNotificationsJob: processing due notifications', ['count' => count($due)]);
        $this->notificationHandler->handleNotifications($due);
    }

    public function getHook(): string
    {
        return self::HOOK;
    }

    public function getMaxAttempts(): int
    {
        // The poller itself does not retry on failure — it will run again in 60 seconds
        return 1;
    }
}
