<?php
namespace R2_Offload\Queue;

use R2_Offload\Logger;

defined( 'ABSPATH' ) || exit;

/**
 * Thin queue abstraction. Prefers Action Scheduler when present; falls back to WP-Cron.
 */
final class Scheduler {

	private Logger $logger;

	public function __construct( Logger $logger ) {
		$this->logger = $logger;
	}

	public function register(): void {
		add_action( 'r2_offload_cron_tick', [ $this, 'cron_tick' ] );
	}

	public function enqueue_attachment( int $attachment_id, int $delay_seconds = 5 ): void {
		if ( function_exists( 'as_enqueue_async_action' ) ) {
			as_enqueue_async_action( 'r2_offload_process_attachment', [ $attachment_id ], 'r2-offload' );
			return;
		}
		wp_schedule_single_event( time() + $delay_seconds, 'r2_offload_process_attachment', [ $attachment_id ] );
		spawn_cron();
	}

	public function cron_tick(): void {
		// Retry hook; Phase 2 will scan failed items and re-enqueue with backoff.
		$this->logger->info( 'Cron tick.', 'queue' );
	}
}
