<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Cron;

use Numinix\SeekmodoWordPress\Config\RemoteConfig;

final class ConfigPullCron
{
    public const HOOK = 'seekmodo_wp_tenant_snapshot_pull';
    public const RECURRENCE = 'five_minutes';

    public static function register(): void
    {
        if (!function_exists('add_filter')) {
            return;
        }
        add_filter('cron_schedules', [self::class, 'addSchedule']);
        add_action(self::HOOK, [RemoteConfig::class, 'pull']);
    }

    /**
     * @param array<string,array<string,mixed>> $schedules
     * @return array<string,array<string,mixed>>
     */
    public static function addSchedule(array $schedules): array
    {
        if (!isset($schedules[self::RECURRENCE])) {
            $schedules[self::RECURRENCE] = [
                'interval' => 5 * 60,
                'display'  => __('Every 5 minutes', 'seekmodo'),
            ];
        }

        return $schedules;
    }

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

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