<?php

namespace Limb_Chatbot\Includes\Services\Jobs\Managers;

/**
 * Job Lock Manager
 *
 * Handles processing locks to prevent concurrent processing of the same job.
 *
 * @since 1.1.0
 */
class Job_Lock_Manager {

	/**
	 * Lock timeout in seconds.
	 *
	 * @var int
	 * @since 1.1.0
	 */
	private int $lock_timeout = 60;

	/**
	 * Constructor.
	 *
	 * @param  int  $lock_timeout  Lock timeout in seconds.
	 *
	 * @since 1.1.0
	 */
	public function __construct( int $lock_timeout = 60 ) {
		$this->lock_timeout = $lock_timeout;
	}

	/**
	 * Acquire processing lock for a job.
	 *
	 * Uses WordPress transients to prevent concurrent processing.
	 *
	 * @param  int  $job_id  Job ID.
	 *
	 * @return bool True if lock acquired, false if already locked.
	 * @since 1.1.0
	 */
	public function acquire( int $job_id ): bool {
		$lock_key = $this->get_lock_key( $job_id );

		// Check if lock already exists
		if ( false !== get_transient( $lock_key ) ) {
			return false;
		}

		// Set lock with timeout
		set_transient( $lock_key, time(), $this->lock_timeout );

		return true;
	}

	/**
	 * Release processing lock for a job.
	 *
	 * @param  int  $job_id  Job ID.
	 *
	 * @return void
	 * @since 1.1.0
	 */
	public function release( int $job_id ): void {
		$lock_key = $this->get_lock_key( $job_id );
		delete_transient( $lock_key );
	}

	/**
	 * Get lock key for a job.
	 *
	 * @param  int  $job_id  Job ID.
	 *
	 * @return string Lock key.
	 * @since 1.1.0
	 */
	private function get_lock_key( int $job_id ): string {
		return 'lbaic_job_processing_lock_' . $job_id;
	}
}
