<?php
	
	namespace Main\Core\Jobs;
	
	class FailedJobsManager
	{
		public static function addFailedJob(string $name, string $payload, string $error, int $maxAttempts = 3): void
		{
			$add = db()->prepare("INSERT INTO FailedJobs (name, payload, maxAttempts, error, lastRetryAt, createdAt) VALUES (?, ?, ?, ?, ?, ?)");
			$add->execute([$name, $payload, $maxAttempts, $error, datetime(), datetime()]);
		}
		
		public static function getNextFailedJob(): ?array
		{
			$failedJobs = db()->query("SELECT * FROM FailedJobs WHERE (lastRetryAt >= DATE_SUB(NOW(), INTERVAL 1 DAY) OR lastRetryAt IS NULL) AND attempts < maxAttempts AND isProcessing = '0' ORDER BY id ASC LIMIT 1 FOR UPDATE");
			return $failedJobs->fetch() ?: null;
		}
		
		public static function lockFailedJob(int $id): void
		{
			$lock = db()->prepare("UPDATE FailedJobs SET attempts = attempts + 1, lastRetryAt = ?, isProcessing = '1' WHERE id = ?");
			$lock->execute([datetime(), $id]);
		}

		public static function releaseFailedJob(int $id, ?string $error = null): void
		{
			if ($error !== null) {
				$release = db()->prepare("UPDATE FailedJobs SET isProcessing = '0', error = ? WHERE id = ?");
				$release->execute([$error, $id]);
			} else {
				$release = db()->prepare("UPDATE FailedJobs SET isProcessing = '0' WHERE id = ?");
				$release->execute([$id]);
			}
		}
		
		public static function removeFailedJob(int $id): void
		{
			$delete = db()->prepare("DELETE FROM FailedJobs WHERE id = ?");
			$delete->execute([$id]);
		}
	}