<?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;

use BookiFlex\Core\Admin\Lifecycle\AbstractExtensionActivator;
use BookiFlex\Core\Contract\Queue\QueueInterface;
use BookiFlex\Extensions\Notification\Service\Jobs\PollDueNotificationsJob;
use BookiFlex\Extensions\Notification\Service\Jobs\PurgeOldNotificationsJob;
use Psr\Log\LoggerInterface;

defined( 'ABSPATH' ) || exit;

class Activator extends AbstractExtensionActivator
{
    public function __construct(
        private readonly QueueInterface $queue,
        private readonly ?LoggerInterface $logger = null
    ) {
    }

    public function getSchemas(): array
    {
        return [
            ORM\Schema\NotificationSchema::class,
        ];
    }

    public function install(): void
    {
        // Cancel any legacy per-notification jobs that may still be in the queue
        $this->queue->cancelAll('bookiflex_send_notification');
    }

    public function enableRuntimeResources(): void
    {
        $this->logger?->debug('Notification: Enabling runtime resources');

        // Cancel existing to ensure clean state (idempotent)
        $this->queue->cancelAll(PollDueNotificationsJob::HOOK);
        $this->queue->cancelAll(PurgeOldNotificationsJob::HOOK);

        // Schedule recurring polling job (every 60 seconds)
        $this->queue->scheduleRecurring(PollDueNotificationsJob::HOOK, [], 60);

        // Schedule weekly purge of old notifications for completed reservations (first run at 04:00)
        $this->queue->scheduleRecurring(PurgeOldNotificationsJob::HOOK, [], 7 * DAY_IN_SECONDS, self::nextNightTime(4, 0));

        $this->logger?->debug('Notification: Runtime resources enabled');
    }

    public function disableRuntimeResources(): void
    {
        $this->logger?->debug('Notification: Disabling runtime resources');

        $this->queue->cancelAll(PollDueNotificationsJob::HOOK);
        $this->queue->cancelAll(PurgeOldNotificationsJob::HOOK);

        $this->logger?->debug('Notification: Runtime resources disabled');
    }
}
