<?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;

/**
 * Synchronous queue implementation for testing
 *
 * Executes tasks immediately instead of queueing them.
 * Useful for unit tests and development environments.
 */
class SyncQueue implements QueueInterface
{
    private array $scheduledTasks = [];

    public function enqueue(string $hook, array $args = [], int $priority = 10): void
    {
        // In sync mode, execute immediately by triggering the WordPress action
        do_action($hook, ...$args);
    }

    public function schedule(string $hook, array $args, \DateTimeInterface $when, int $priority = 10): void
    {
        // Store for inspection in tests, but don't execute
        $this->scheduledTasks[] = [
            'hook' => $hook,
            'args' => $args,
            'when' => $when,
            'priority' => $priority,
        ];
    }

    public function cancel(string $hook, array $args = []): void
    {
        // Remove from scheduled tasks if exists
        $this->scheduledTasks = array_filter(
            $this->scheduledTasks,
            fn($task) => $task['hook'] !== $hook || (!empty($args) && $task['args'] !== $args)
        );
    }

    public function cancelAll(string $hook): void
    {
        // Remove all tasks with this hook
        $this->scheduledTasks = array_filter(
            $this->scheduledTasks,
            fn($task) => $task['hook'] !== $hook
        );
    }

    public function scheduleRecurring(string $hook, array $args, int $intervalSeconds, ?\DateTimeInterface $startAt = null, int $priority = 10): void
    {
        // Store for inspection in tests, but don't execute recurring tasks
        $this->scheduledTasks[] = [
            'hook'     => $hook,
            'args'     => $args,
            'interval' => $intervalSeconds,
            'startAt'  => $startAt,
            'priority' => $priority,
            'type'     => 'recurring',
        ];
    }

    /**
     * Get all scheduled tasks (for testing purposes)
     *
     * @return array
     */
    public function getScheduledTasks(): array
    {
        return $this->scheduledTasks;
    }

    /**
     * Clear all scheduled tasks (for testing purposes)
     */
    public function clearScheduledTasks(): void
    {
        $this->scheduledTasks = [];
    }
}
