<?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;

/**
 * Bulk Sync Quantities API Route
 *
 * Triggers a bulk quantity synchronization that fetches all stock from /stockall
 * and updates WooCommerce product variations with stock data and metadata.
 *
 * POST /wp-json/actionwear-api/v1/bulk_sync_quantities
 */
$route = new Action_Wear_Api_Route("/bulk_sync_quantities");
$route->setMethods("POST");
$route->setCallback(function () {

    $response = new ApiResponse();

    // Guard: 409 if already active in quantity_sync conflict group
    if (JobQueue::hasRunning('quantity_sync') || JobQueue::hasPending('bulk_quantity_fetch')) {
        $response->error("Bulk quantity sync is already running", 409);
        return $response->getResponse();
    }

    JobQueue::push('bulk_quantity_fetch', null, 30, null, 'quantity_sync');

    $response->success([
        'queued' => true,
        'timestamp' => time()
    ], "Bulk quantity sync task created successfully!");
    return $response->getResponse();
});
$route->registerRoute();
