<?php
	namespace Api\Core\Jobs;
	
	use Exception;
	
	class Worker
	{
		public static function processJob(string $payload): bool
		{
			$job = unserialize($payload);
			if (!$job instanceof Job) {
				error_log('Worker: Invalid job payload, not a Job instance');
				return false;
			}
			try {
				$job->handle();
				return true;
			} catch (Exception $e) {
				FailedJobsManager::addFailedJob(
					$job->getName() ?? 'UnknownJob',
					$payload,
					$e->getMessage(),
					$job->getMaxAttempts() ?? 3
				);
				return false;
			}
		}
		
		public static function processFailedJob(array $failedJob): bool
		{
			if ($failedJob['isProcessing'] == '1') {
				return false;
			}

			if ($failedJob['attempts'] >= $failedJob['maxAttempts']) {
				return false;
			}

			FailedJobsManager::lockFailedJob($failedJob['id']);

			try {
				$job = unserialize($failedJob['payload']);
				
				if (!$job instanceof Job) {
					// Invalid job payload, remove from failed jobs
					FailedJobsManager::removeFailedJob($failedJob['id']);
					return false;
				}
				
				// Attempt to process the job
				$job->handle();
				
				// If successful, remove from failed jobs
				FailedJobsManager::removeFailedJob($failedJob['id']);

				return true;
			} catch (Exception $e) {
				FailedJobsManager::releaseFailedJob($failedJob['id'], $e->getMessage());
				return false;
			}
		}
	}