<?php

namespace HelpGent\App\Providers;

defined( 'ABSPATH' ) || exit;

use Exception;
use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\App\BackgroundServices\MediaTransferService;

class MediaTransferProcessorProvider implements Provider {
    public function boot() {
        add_action( 'init', [ $this, 'init_background_processor' ] );
        add_action( 'init', [ $this, 'run_background_processor' ], 12 );
    }

    public function init_background_processor(): void {
        $GLOBALS['helpgent_media_transfer_service'] = helpgent_singleton( MediaTransferService::class );
    }

    public function run_background_processor(): void {
        /**
         * @var ?MediaTransferService $helpgent_media_transfer_service
         */
        global $helpgent_media_transfer_service;

        if ( ! $helpgent_media_transfer_service ) {
            return;
        }

        if ( ! $helpgent_media_transfer_service->is_expired() ) {
            return;
        }

        try {
            $helpgent_media_transfer_service->run();
        } catch ( Exception $e ) {
        }
    }
}