<?php

namespace HelpGent\App\Providers;

defined( 'ABSPATH' ) || exit;

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

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

    public function init_background_service(): void {
        $GLOBALS['helpgent_media_clean_up_service'] = helpgent_singleton( MediaCleanUpService::class );
    }

    public function run_background_processor(): void {
        /**
         * @var MediaCleanUpService $helpgent_media_clean_up_service
         */
        global $helpgent_media_clean_up_service;

        if ( ! $helpgent_media_clean_up_service ) {
            return;
        }

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

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