<?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_Product_Differential as CatalogEntity;
use AC_SYNC\Includes\Classes\Product\Action_Wear_Product as Product;
use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;

class Action_Wear_Diff_Catalog_Handler implements Action_Wear_Job_Handler_Interface
{
    public function handle(object $job, array $payload): JobResult
    {
        global $wpdb;

        // Truncates moved inside generateProducts() and generateImages()
        // so they only run AFTER the API has responded successfully
        Product::filterDeletedProducts();

        // Queue the 3 catalog generate jobs (they share catalog_sync conflict group, run sequentially)
        JobQueue::push('catalog_generate_categories', null, 80, null, 'catalog_sync');
        JobQueue::push('catalog_generate_products', null, 80, null, 'catalog_sync');
        JobQueue::push('catalog_generate_images', null, 80, null, 'catalog_sync');

        Log::write("DiffCatalog: Queued catalog generation tasks", Log::INFO, Log::CONTEXT_CRONJOB);

        // Update execution time on the entity
        $entity = new CatalogEntity();
        $entity->updateExecutionTime();

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

        return JobResult::success();
    }
}
