<?php
namespace FuseCommerce\Hooks;
if ( ! defined( 'ABSPATH' ) ) exit;

use FuseCommerce\Hooks\IHook;
use FuseCommerce\Jobs\Cron;
use FuseCommerce\Jobs\IndexProducts;
use FuseCommerce\Models\IndexingState;

class ActionCron implements IHook {

    static function register() {
        add_action(Cron::FUSE_COMM_HEARTBEAT, [self::class, 'on_fuse_heartbeat']);
    }

    static function on_fuse_heartbeat() {
        // Check if there's an active indexing process
        $state = IndexingState::load();

        // Only run if there's a working process (not idle, not completed, not error)
        if ( $state === null || ! $state->isWorking() ) {
            return;
        }

        // Run the IndexProducts job to continue indexing
        $job = new IndexProducts();

        if ( $job->canRun() ) {
            $job->run();
        }
    }
}