<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Cron;

use Numinix\SeekmodoWordPress\Events\EventsQueue;

final class EventsFlushCron
{
    public const HOOK = 'seekmodo_wp_events_flush';

    public static function register(): void
    {
        if (!function_exists('add_action')) {
            return;
        }
        add_action(self::HOOK, [self::class, 'tick']);
    }

    public static function tick(): void
    {
        // Drain up to 200 events per tick. EventsQueue::flush() POSTs
        // to /v1/events via Client::sendEvents() and deletes the rows
        // on a 2xx ack. Unreachable gateway -> rows are kept for the
        // next tick (retention-pruned at 7d).
        EventsQueue::flush();
    }

    public static function schedule(): void
    {
        if (!function_exists('wp_next_scheduled')) {
            return;
        }
        if (wp_next_scheduled(self::HOOK) === false) {
            wp_schedule_event(time() + 60, 'minutely_or_default', self::HOOK);
        }
    }

    public static function unschedule(): void
    {
        if (!function_exists('wp_clear_scheduled_hook')) {
            return;
        }
        wp_clear_scheduled_hook(self::HOOK);
    }
}
