<?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 Prices API Route
 *
 * Triggers a bulk price synchronization that fetches all prices from /pricesall
 * and updates WooCommerce product variations with calculated recharges.
 *
 * POST /wp-json/actionwear-api/v1/bulk_sync_prices
 */
$route = new Action_Wear_Api_Route("/bulk_sync_prices");
$route->setMethods("POST");
$route->setCallback(function () {

    $response = new ApiResponse();

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

    JobQueue::push('bulk_price_fetch', null, 30, null, 'price_sync');

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