<?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("/get_queue_items");
$route->setMethods("GET");
$route->setCallback(function () {
  $response = new ApiResponse();

  $jobs = JobQueue::getJobs(['status' => ['pending', 'claimed', 'failed']], 200);

  $jobTypeLabels = [
    'product_import'              => 'Import Prodotto',
    'images_update'               => 'Aggiornamento Immagini',
    'bulk_price_fetch'            => 'Sync Prezzi Bulk (fetch)',
    'bulk_price_batch'            => 'Sync Prezzi Bulk (batch)',
    'bulk_quantity_fetch'         => 'Sync Quantità Bulk (fetch)',
    'bulk_quantity_batch'         => 'Sync Quantità Bulk (batch)',
    'diff_price'                  => 'Sync Differenziale Prezzi',
    'diff_quantity'               => 'Sync Differenziale Quantità',
    'diff_catalog'                => 'Sync Differenziale Catalogo',
    'catalog_generate_categories' => 'Generazione Categorie',
    'catalog_generate_products'   => 'Generazione Prodotti',
    'catalog_generate_images'     => 'Generazione Immagini',
  ];

  $queue = [];
  foreach ($jobs as $job) {
    $payload = $job->payload ? json_decode($job->payload, true) : [];
    $item = [
      'id'           => (int) $job->id,
      'job_type'     => $job->job_type,
      'status'       => $job->status,
      'label'        => $jobTypeLabels[$job->job_type] ?? $job->job_type,
      'priority'     => (int) $job->priority,
      'attempts'     => (int) $job->attempts,
      'max_attempts' => (int) $job->max_attempts,
      'available_at' => $job->available_at,
      'created_at'   => $job->created_at,
    ];
    if (!empty($payload['sku'])) {
      $item['sku'] = $payload['sku'];
    }
    $queue[] = $item;
  }

  $response->success(["queue" => $queue]);
  return $response->getResponse();
});
$route->registerRoute();
