<?php

declare(strict_types=1);

namespace Instinctor\Core\Queue;

if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * WordPress queue driver.
 *
 * Extends DatabaseDriver — all job storage and processing is identical.
 * Adds WP-cron scheduling so the runner fires automatically every minute.
 *
 * WP-cron fires on page load — not a true cron. For high-volume stores,
 * disable WP-cron (DISABLE_WP_CRON = true) and add a real system cron:
 *   * * * * * curl -s https://example.com/wp-cron.php?doing_wp_cron
 *
 * The 'instinctor_queue_runner' WP-cron hook calls Queue::run() which
 * processes up to 50 pending jobs per tick.
 */
class WordPressDriver extends DatabaseDriver
{
    private const CRON_HOOK     = 'instinctor_queue_runner';
    private const CRON_SCHEDULE = 'instinctor_every_minute';

    public function __construct()
    {
        // Register the 'every_minute' schedule if not already there
        add_filter('cron_schedules', [$this, 'registerSchedule']);

        // Register the hook that fires the runner
        add_action(self::CRON_HOOK, [$this, 'runFromCron']);

        // Schedule the event on first boot
        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time(), self::CRON_SCHEDULE, self::CRON_HOOK);
        }
    }

    /** @internal */
    public function registerSchedule(array $schedules): array
    {
        if (!isset($schedules[self::CRON_SCHEDULE])) {
            $schedules[self::CRON_SCHEDULE] = [
                'interval' => 60,
                'display'  => 'Every Minute (Instinctor Queue)',
            ];
        }
        return $schedules;
    }

    /** @internal — Called by WP-cron */
    public function runFromCron(): void
    {
        $this->run(50);
    }

    /**
     * Unschedule the runner cron event.
     * Called from plugin deactivation hook.
     */
    public static function unschedule(): void
    {
        $timestamp = wp_next_scheduled(self::CRON_HOOK);
        if ($timestamp) {
            wp_unschedule_event($timestamp, self::CRON_HOOK);
        }
    }
}
