<?php
if (!defined('ABSPATH'))
  exit; // Exit if accessed directly
use AC_SYNC\Includes\Classes\Api\Action_Wear_Api_Route;
use AC_SYNC\Includes\Classes\Api\Action_Wear_API_Response as ApiResponse;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Queue as JobQueue;

$route = new Action_Wear_Api_Route("/retry_failed_jobs");
$route->setMethods("POST");
$route->setCallback(function () {
  $response = new ApiResponse();

  $data = json_decode(file_get_contents("php://input"));
  $id = isset($data->id) ? (int) $data->id : null;

  if ($id) {
    // Retry single job
    $ok = JobQueue::retryJob($id);
    if (!$ok) {
      $response->fail("Job not found or not in failed state");
      return $response->getResponse();
    }
    $response->success(['retried' => 1]);
  } else {
    // Retry all failed
    $count = JobQueue::retryAllFailed();
    $response->success(['retried' => $count]);
  }

  return $response->getResponse();
});
$route->registerRoute();
