<?php
/**
 * Bulk job repository.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Stores and schedules persistent bulk jobs.
 */
class SmartyPress_AI_Content_Generator_Bulk_Job_Repository {

	/**
	 * Job option prefix.
	 *
	 * @var string
	 */
	private $option_prefix;

	/**
	 * Cron hook.
	 *
	 * @var string
	 */
	private $cron_hook;

	/**
	 * Constructor.
	 *
	 * @param string $option_prefix Option prefix.
	 * @param string $cron_hook Cron hook.
	 */
	public function __construct( $option_prefix, $cron_hook ) {
		$this->option_prefix = (string) $option_prefix;
		$this->cron_hook     = (string) $cron_hook;
	}

	/**
	 * Get job option name.
	 *
	 * @param string $job_id Job ID.
	 * @return string
	 */
	public function get_option_name( $job_id ) {
		return $this->option_prefix . sanitize_key( $job_id );
	}

	/**
	 * Get job.
	 *
	 * @param string $job_id Job ID.
	 * @return array|null
	 */
	public function get( $job_id ) {
		$job = get_option( $this->get_option_name( $job_id ), null );

		return is_array( $job ) ? $job : null;
	}

	/**
	 * Save job.
	 *
	 * @param array $job Job data.
	 * @return void
	 */
	public function save( array $job ) {
		update_option( $this->get_option_name( $job['id'] ), $job, false );
	}

	/**
	 * Schedule a job if it is not already scheduled.
	 *
	 * @param string $job_id Job ID.
	 * @return void
	 */
	public function schedule( $job_id ) {
		if ( ! wp_next_scheduled( $this->cron_hook, array( $job_id ) ) ) {
			wp_schedule_single_event( time() + 5, $this->cron_hook, array( $job_id ) );
		}
	}
}
