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

class Action_Wear_Sku_Cleanup_Handler implements Action_Wear_Job_Handler_Interface
{
    const UPDATE_TIMING = 21600; // 6 hours

    public function handle(object $job, array $payload): JobResult
    {
        $cleaned = Product::cleanupDuplicateSkus();

        if ($cleaned > 0) {
            Log::write("SkuCleanupHandler: Removed {$cleaned} duplicate product(s)", Log::INFO, Log::CONTEXT_CRONJOB);
        }

        // Self-reschedule
        $nextRun = gmdate('Y-m-d H:i:s', time() + self::UPDATE_TIMING);
        JobQueue::push('sku_cleanup', null, 90, $nextRun, null, 3, (int) $job->id);

        return JobResult::success();
    }
}
