<?php
if (!defined('ABSPATH'))
  exit;

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;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Runner as JobRunner;
use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;

$route = new Action_Wear_Api_Route("/purge_all_jobs");
$route->setMethods("POST");

$route->setCallback(function () {
  global $wpdb;

  $response = new ApiResponse();

  // Cancel/delete from custom queue
  $table = $wpdb->prefix . 'actionwear_jobs';
  $wpdb->query("DELETE FROM {$table} WHERE status IN ('pending', 'claimed', 'failed', 'completed', 'cancelled')");
  $deleted = (int) $wpdb->rows_affected;

  // Release runner lock if held
  JobRunner::forceRelease();

  // Also cancel from Action Scheduler if active
  if (function_exists('as_unschedule_all_actions')) {
    as_unschedule_all_actions('', null, 'actionwear');
  }

  Log::write("Purge all jobs: Deleted {$deleted} custom jobs and cancelled all AS actions", Log::WARNING, Log::CONTEXT_GENERAL);

  $response->success([
    "success" => true,
    "deleted" => $deleted,
    "message" => "Tutti i job eliminati"
  ]);
  return $response->getResponse();
});

$route->registerRoute();
