<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\LocalIndex;

use Numinix\SeekmodoWordPress\Cron\IndexCron;

/**
 * Schedules local index delta ticks alongside gateway indexer.
 */
final class LocalIndexCron
{
    public const HOOK = Indexer::CRON_HOOK;

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

    public static function schedule(): void
    {
        if (!function_exists('wp_next_scheduled') || !function_exists('wp_schedule_event')) {
            return;
        }
        if (!wp_next_scheduled(self::HOOK)) {
            wp_schedule_event(time() + 120, IndexCron::RECURRENCE, self::HOOK);
        }
    }

    public static function unschedule(): void
    {
        if (!function_exists('wp_next_scheduled') || !function_exists('wp_unschedule_event')) {
            return;
        }
        $ts = wp_next_scheduled(self::HOOK);
        while ($ts) {
            wp_unschedule_event($ts, self::HOOK);
            $ts = wp_next_scheduled(self::HOOK);
        }
    }
}
