<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Service\Queue;

use BookiFlex\Core\Contract\Queue\QueueInterface;

defined( 'ABSPATH' ) || exit;

/**
 * Action Scheduler implementation of QueueInterface
 *
 * Wraps WooCommerce Action Scheduler for reliable background task processing
 */
class ActionSchedulerQueue implements QueueInterface
{
    private const GROUP = 'bookiflex';

    public function enqueue(string $hook, array $args = [], int $priority = 10): void
    {
        if (!function_exists('as_enqueue_async_action')) {
            throw new \RuntimeException('Action Scheduler is not available. Please ensure it is installed and loaded.');
        }

        as_enqueue_async_action(
            $hook,
            $args,
            self::GROUP,
            true, // unique
            $priority
        );
    }

    public function schedule(string $hook, array $args, \DateTimeInterface $when, int $priority = 10): void
    {
        if (!function_exists('as_schedule_single_action')) {
            throw new \RuntimeException('Action Scheduler is not available. Please ensure it is installed and loaded.');
        }

        as_schedule_single_action(
            $when->getTimestamp(),
            $hook,
            $args,
            self::GROUP,
            true, // unique
            $priority
        );
    }

    public function cancel(string $hook, array $args = []): void
    {
        if (!function_exists('as_unschedule_action')) {
            return;
        }

        as_unschedule_action(
            $hook,
            $args,
            self::GROUP
        );
    }

    public function cancelAll(string $hook): void
    {
        if (!function_exists('as_unschedule_all_actions')) {
            return;
        }

        as_unschedule_all_actions(
            $hook,
            [],
            self::GROUP
        );
    }

    public function scheduleRecurring(string $hook, array $args, int $intervalSeconds, ?\DateTimeInterface $startAt = null, int $priority = 10): void
    {
        if (!function_exists('as_schedule_recurring_action')) {
            throw new \RuntimeException('Action Scheduler is not available. Please ensure it is installed and loaded.');
        }

        as_schedule_recurring_action(
            $startAt ? $startAt->getTimestamp() : time(),
            $intervalSeconds,
            $hook,
            $args,
            self::GROUP,
            true, // unique
            $priority
        );
    }
}
