<?php

namespace AC_SYNC\Includes\Classes\Async\Handlers;

if (!defined('ABSPATH')) exit;

use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Handler_Interface;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Result as JobResult;
use AC_SYNC\Includes\Classes\Async\Action_Wear_Job_Queue as JobQueue;
use AC_SYNC\Includes\Classes\Differential\Entities\Action_Wear_Quantity as QuantityEntity;
use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;

class Action_Wear_Diff_Quantity_Handler implements Action_Wear_Job_Handler_Interface
{
    public function handle(object $job, array $payload): JobResult
    {
        $entity = new QuantityEntity();
        $entity->execute();
        $entity->updateExecutionTime();

        Log::write("DiffQuantity: Differential quantity sync completed, next in " . $entity->getUpdateTiming() . "s", Log::INFO, Log::CONTEXT_CRONJOB);

        // Self-reschedule
        $nextRun = gmdate('Y-m-d H:i:s', time() + $entity->getUpdateTiming());
        JobQueue::push('diff_quantity', null, 60, $nextRun, 'quantity_sync', 5, (int) $job->id);

        return JobResult::success();
    }
}
